本人菜鸟一枚,刚开始学习socket,之前写了简单的服务器和客户端的并发通讯,都通过了。
然后试着写一些客户端监听和回调的写法,因为客户端不是随时都在发送信息,所以需要
在监听到信息后,服务器再做出反应。
运行都是可以的,但是却没有得到想要的结果,请大家帮忙看看,是哪里的逻辑问题。应该
怎么处理这样的业务逻辑呢?谢谢大家了
try{
server = new ServerSocket(2888);
out.println("服务器开始监听");
}catch(IOException ex){
out.println(ex.toString()+":打开服务器监听错误");
);
}
new Thread(new Runnable(){
public void run(){
try{
while(a){
socket = server.accept();
if(socket!=null){
out.println(socket.getInetAddress().getHostAddress()+"有连接进入");
writer = new WiterTo();
writer.setSocket(socket);
writer.setStr("服务器收到你的消息");
writer.start();
//开始监听
ClientListener cLis = new ClientListener();
read = new Read();
read.setSocket(socket);
cLis.setRead(read);
cLis.setCallBack(new callBack(){
public int isMsg(){
writer.setStr("接收到你的消息,"+countSocket);
writer.start();
return 0;
}
});
cLis.start();
read.start();
clientIp = clientIp+socket.getInetAddress()+"进入时间"+df.format(new Date())+"<br>";
mapSocket.put(countSocket,socket);
application.setAttribute("clientSocket",mapSocket);
countSocket++;
//dis = new DataInputStream(socket.getInputStream());
//dos = new DataOutputStream(socket.getOutputStream());
}
}
//server.close();
}catch(IOException ex){
out.print(ex.toString()+":线程错误");
}
-----------------------------其他类部分-----------------------------------
//读取类
class Read extends Thread{
DataInputStream dis = null;
boolean state = true;
Socket socket = null;
String str = null;
public void setSocket(Socket socket){this.socket = socket;}
public String getStr(){
return this.str;
}
private void readFrom(){
if(socket!=null){
try{
//初始化输入流
dis = new DataInputStream(socket.getInputStream());
boolean a = true;
while(a){
if(dis!=null){
str = dis.readUTF();
}
}
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}
public void run(){
readFrom();
}
}
//输出类
class WiterTo extends Thread{
DataOutputStream dos = null;
Socket socket = null;
String con = null;
public void setSocket(Socket socket){this.socket = socket;}
public void setStr(String str){
this.con = str;
}
private void wite(){
boolean state = true;
if(socket!=null){
try{
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(con);
dos.flush();
}catch(Exception ex){
System.out.println(ex.toString());
}
}else{
//return null;
}
}
public void run(){
wite();
}
}
//回调接口
public interface callBack{
public int isMsg();
}
//监听客户端是否有信息发过来
class ClientListener extends Thread{
Socket socket = null;
callBack rm;
Read read;
public void setRead(Read read){
this.read = read;
}
public void setCallBack(callBack rm){
this.rm = rm;
}
private void listener(Read read){
while(true){
if(read.getStr()!=null){
rm.isMsg();
}
}
}
public void run(){
listener(read);
}
}
请大家帮忙看看,服务器没有收到消息,但是如果把监听去掉,换成dis和dos,服务器能接收到10个连接。