首先启动服务器,当只有一个客户端的时候,能够正常通信,当有多个客户端的时候,客户端发送给服务器的能正常,可服务器发送给客户端的就不一定哪一个收到了。我想问下如何修改代码能让所有客户端都能收到服务器发送的代码,就是说服务器发送一条消息,所有的客户端都接收到。
服务器的代码如下
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(7778);
while(true)
{
Socket socket = ss.accept();
new ServerInputThread(socket).start();
new ServerOutputThread(socket).start();
}
}
}
class ServerInputThread extends Thread
{
private Socket socket;
public ServerInputThread(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
while(true)
{
String str = dis.readUTF();
System.out.println(str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ServerOutputThread extends Thread
{
private Socket socket;
public ServerOutputThread(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
OutputStream os = socket.getOutputStream();
DataOutputStream dis = new DataOutputStream(os);
while(true)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
dis.writeUTF(str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
客户端的代码:
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("127.0.0.1", 7778);
new ClientInputThread(socket).start();
new ClientOutputThread(socket).start();
}
}
class ClientInputThread extends Thread
{
private Socket socket;
public ClientInputThread(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
while(true)
{
String str = dis.readUTF();
System.out.println(str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class ClientOutputThread extends Thread
{
private Socket socket;
public ClientOutputThread(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
OutputStream os = socket.getOutputStream();
DataOutputStream dis = new DataOutputStream(os);
while(true)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
dis.writeUTF(str);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}