Java网络,无法弄清楚多线程服务器有什么问题

时间:2016-06-11 14:26:14

标签: java multithreading

我的名字是Jędrzej,我是新来的。我试图在java中编写一个简单的聊天。我正在尝试制作多线程服务器,以便多个客户端可以连接到此服务器。我的客户端工作正常,但如果我运行两个客户端,他们不会看到彼此的响应。代码:'

package serverthread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerWIthThreads {

    public static void main(String[] args){

        try{
            ServerSocket serverSocket = new ServerSocket(1234);
            while(true){
                Socket socket = serverSocket.accept();
                Runnable r = new ThreadForServer(socket);
                Thread t = new Thread(r);
                t.start();

            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

}



  package serverthread;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ThreadForServer implements Runnable{

    private Socket socket;
    private ObjectInputStream inputStream;
    private ObjectOutputStream outputStream;
    public ThreadForServer(Socket i){

        socket = i;

    }

    @Override
    public void run(){

        try{
            inputStream = new ObjectInputStream(socket.getInputStream());
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.flush();

            while(true){
                String message = (String) inputStream.readObject();
                outputStream.writeObject(message);
                outputStream.flush();
            }

        }catch(IOException e){

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }



}

`

1 个答案:

答案 0 :(得分:0)

您实施此方式的方式是,您正在从一个客户端读取邮件,然后将其写回相同的客户端。

您需要修改程序,以便将邮件写入其他已连接客户端的Socket