socket多线程的问题

java当中socket多线程是怎样写可以将所有客户发来的消息数记录下来并显示给客户,客户当前跟服务器说的是第几句话,比如第一个客户:0:0:aa
服务器回复aa
第一个客户:1:1:bb
服务器回复bb
第二个客户:2:0:aa
服务器回复aa
第二个客户:3:1:bb
第一个数是总行数,第二个是当前客户行数第三个就是内容了现在这个程序已经完成了后两个,第一个总行数咋实现 谁给发个代码啥的谢谢最好能在这里加
package DemoServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SocketHandler;

import org.w3c.dom.css.Counter;

public class Server {
public static void main(String[] args) throws IOException

{

int port = 8821;

    ServerSocket serverSocket = new ServerSocket(port);   
    ExecutorService exe = Executors.newFixedThreadPool(   //只有一个ExecutorService,执行   
                         Runtime.getRuntime().availableProcessors()*10);   
     while(true)   
    {   
         Socket socket = serverSocket.accept();   
         exe.execute(getTask(socket)); //开启多个线程   
    }       
}   

public static Runnable getTask(final Socket s)   
{   

// Map lines = new HashMap();
return new Runnable(){

private BufferedReader br = null;

private PrintWriter pw = null;

private Socket socket = null;

private int number = 0;
// private int count;

        public void run() {   
            try {   
                this.socket = s; //socket可以传递   
                System.out.println("接收到客户端的数据");   

                br = getReader(socket);   
                pw = getWriter(socket); 
                //从客户端读   
                String msg = null; 
                while (( msg = br.readLine()) != null) { 
                System.out.println(msg); 
                    number++; 
                pw.println(count +":" + number +":"+ msg); 
                    if(msg.equals("bye")) //注意,没有这句不能退出while   
                        break;  

                } 
                //向客户端写 
                pw.println("数据正确");   
            } catch (IOException ex) {   
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);   
            } finally {   
                try {   
                    if(socket!=null)   
                    socket.close();   
                } catch (IOException ex) {   
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);   
                }   
            }  
        }   

        //从客户端读数据   
        private BufferedReader getReader(Socket socket) throws IOException {   
            InputStream input = socket.getInputStream(); 
            return new BufferedReader(new InputStreamReader(input));   
        }   

        //向客户端写数据   
        private PrintWriter getWriter(Socket socket) throws IOException {   
            OutputStream output = socket.getOutputStream(); 
            return new PrintWriter(new OutputStreamWriter(output),true);//注意true是提醒刷新   
        } 


    };   
} 

}

2个回答

具体代码 给你
客户端
import java.io.*;
import java.net.*;

public class Clinet
{

public static void main(String[] args) 
{
    InetAddress ia = null;
    Socket s = null;                                               
    BufferedReader is = null;
    BufferedWriter os = null;
    PrintWriter pw = null;
    BufferedReader br = null;
    BufferedWriter bw = null;

    try {
        ia= InetAddress.getByName("127.0.0.1");
        //          System.out.println(ia.getHostAddress());
        //          System.out.println(ia.getHostName());
        s= new Socket(ia, 9001);
        is = new BufferedReader(new InputStreamReader(s.getInputStream()));
        pw = new PrintWriter(s.getOutputStream(), true);
        br = new BufferedReader(new InputStreamReader(System.in));
        //            System.out.println("输入路径:");
        //          String msg = br.readLine();
        //          pw.println(msg);
        Thread2 t = new Thread2(is);
        while(true)
        {
            try{
                t.start();

// System.out.println("您说:");
String msg1 = br.readLine();
pw.println(msg1);
}
catch (java.lang.IllegalThreadStateException e)
{

// System.out.println("您说:");
String msg1 = br.readLine();
pw.println(msg1);
}

        }





    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        //          e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //          e.printStackTrace();
    }


}

}

class Thread2 extends Thread
{
BufferedReader br ;
public Thread2(BufferedReader br)
{
this.br = br;
}
public void run()
{
while(true)
{
try {
String msg = br.readLine();
System.out.println("服务端说:"+msg);
sleep(1000);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
}
}

服务器端
import java.io.*;
import java.net.*;

public class Sever {

public static void main(String[] args) 
{
    ServerSocket ss = null; 
    Socket  s = null;
    BufferedReader is = null;
    OutputStream os = null;
    //      PrintWriter pw = null;
    PrintStream pw = null;
    File f = null;

    BufferedReader filebr = null;
    try 
    {
        ss = new ServerSocket(9001);
        System.out.println("加载中");
        s = ss.accept();
        is = new BufferedReader(new InputStreamReader(s.getInputStream()));
        os = s.getOutputStream();
        pw = new PrintStream(s.getOutputStream(), true);
        Thread1 t = new Thread1(is);
        filebr = new BufferedReader(new InputStreamReader(System.in));
        while(true)
        {
            try{
                t.start();

// System.out.println("您说:");
String msg1 = filebr.readLine();
pw.println(msg1);
}
catch (java.lang.IllegalThreadStateException e) {
// System.out.println("您说:");
String msg1 = filebr.readLine();
pw.println(msg1);
}

        }




    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        //          e.printStackTrace();
    }



}

}

class Thread1 extends Thread
{
BufferedReader br ;
static int size=0;
public Thread1(BufferedReader br)
{
this.br = br;
}
public void run()
{
size++;
while(true)
{
try {
String msg = br.readLine();
System.out.println("客户端说:"+msg);
sleep(1000);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
}
}
希望可以帮助你

可以再Server类里定义一个静态的变量,每次客户端来消息都将这个常量+1

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!