写了Socket通讯实现群聊,可是发给服务器后,别的客户端缺收不到服务器转发的信息
问题描述:
服务端:
public static void main(String args[]) throws IOException {
QueueSocket queueSocket = new QueueSocket();
queueSocket.ini();
}
public void ini() {
ServerSocket ss = null;
try {
ss = new ServerSocket(8082);
System.out.println("server is starting");
while (true) {
Socket socket = ss.accept();
System.out.println("New connection accepted "
+ socket.getInetAddress() + ":" + socket.getPort());
new HandlerThread(socket);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ss != null) {
ss.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class HandlerThread implements Runnable {
private Socket socket;
String buffer;
public HandlerThread(Socket client) {
this.socket = client;
new Thread(this).start();
}
@Override
public void run() {
try {
//读取服务器端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
//向服务器端发送数据
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String ret = input.readUTF();
out.writeUTF(ret);
out.flush();
System.out.println("客户端返回过来的是: " + ret);
input.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端:
public static void main(String[] args) {
String buffer = "";
Socket socket = null;
try {
socket = new Socket("192.168.1.107", 8082);
if (socket == null) {
System.out.println("error");
}
//读取服务器端数据
DataInputStream input = new DataInputStream(socket.getInputStream());
//向服务器端发送数据
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("A10104");
out.flush();
String ret = input.readUTF();
System.out.println("服务器端返回过来的是: " + ret);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
另一个客户端:
@Override
public void run() {
try {
socket = new Socket("192.168.1.107", 8082);
System.out.println("socket客户端" + Util.getCall(context) + "运行");
if (socket == null) {
System.out.println("error");
}
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("A10104");
out.flush();
while(true){
DataInputStream input = new DataInputStream(socket.getInputStream());
String ret = input.readUTF();
if (!ret.equals("")&&ret!=null) {
System.out.println("服务器端返回过来的是: " + ret);
}
}
//读取服务器端数据
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
求大神帮我看看,项目着急卡在这里了
答
客户端先要主动连服务器端,服务器用数组将建立的连接的socket保存起来,转发的时候找到连接并且发送。