关于java socket实现服务器向指定的客户端发送信息的小程序
小弟刚学socket 目前能实现同时向两个客户端发送信息,想知道怎么能指定一个发,以下是代码:
服务器:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class server {
public static void main(String[] args) throws IOException{
ServerSocket server=new ServerSocket(5678);
List<Socket> list = new ArrayList<Socket>();
while (true){
Socket client=server.accept();
list.add(client);
if(list.size() == 2){
for(Socket socket : list){
PrintWriter out=new PrintWriter(socket.getOutputStream());
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine());
out.println("收到");
out.flush();
}
}
}
}
}
客户端1 c
import java.net.*;
import java.io.*;
public class c{
static Socket server;
public static void main(String[] args)throws Exception{
server=new Socket(InetAddress.getLocalHost(),5678);
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out=new PrintWriter(server.getOutputStream());
while(true){
System.out.println(in.readLine());
}
}
}
客户端2 cc
import java.net.*;
import java.io.*;
public class cc{
static Socket server;
public static void main(String[] args)throws Exception{
server=new Socket(InetAddress.getLocalHost(),5678);
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out=new PrintWriter(server.getOutputStream());
while(true){
System.out.println(in.readLine());
}
}
}
谢谢各位了!!
[解决办法]
把你的增强for循环改掉,list.get(index)返回的是socket对象,调用这个socket对象获取输出流。通过index指定你想输出的客户端