关于java网络编程的基础问题,已经附带源代码

首先启动服务器,当只有一个客户端的时候,能够正常通信,当有多个客户端的时候,客户端发送给服务器的能正常,可服务器发送给客户端的就不一定哪一个收到了。我想问下如何修改代码能让所有客户端都能收到服务器发送的代码,就是说服务器发送一条消息,所有的客户端都接收到。
服务器的代码如下
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();
}
}
}

你需要用一个list 管理 所有的客户端socket 。

Socket socket = ss.accept();
socketList.add(socket )

然后 再依次向么个socket 输出

for (Iterator iterator = socketList.iterator(); iterator.hasNext();) {
Socket object = (Socket) iterator.next();
OutputStream os = socket.getOutputStream();
DataOutputStream dis = new DataOutputStream(os);
dis.writeUTF( “message”);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-09-29
用集合,将客户端一个个放进去,服务器端迭代发送!
相似回答