public class User extends Thread {
private Socket userSocket=null; //和客户端通信的socket
private int connectionId=0; //用户连接id

private InputStream inputStream=null;
private byte userMsgs[] = null; //从客户观接收到的消息




//构造函数
public User(int connectionId,Socket s){
this.connectionId=connectionId;
this.userSocket=s;

try {
this.inputStream=s.getInputStream();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

//开始线程
public void run(){

while(true){
this.processUserMsgs();
}
}

//读取客户端发送来的消息
private void processUserMsgs(){
userMsgs = new byte[10]; //创建用于接收消息的变量
try {
this.inputStream.read(userMsgs); //读取消息报
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//处理客户端消息报数组
for(byte userMsg : userMsgs){
System.out.println(userMsg);
}
}
}
我写了个这样的类``
当客户端连接的时候`` while(true){
this.processUserMsgs();
}
这里this.processUserMsgs();  只有当客户端发消息的时候才被调用,要不然就进不到这里``而当我把客户端关掉的时候``````
他才开始无限循环到这里``this.processUserMsgs();这是啥意思```不是应该本来就会无限循环到这里的么?

解决方案 »

  1.   

    话说我中断设在这里`this.processUserMsgs();
    应该无论客户端有没有发消息都会运行到中断的吧`````
      

  2.   

    程序不完整,不能准确判断。
    一种可能是你判断错误,最好在循环中增加一句调试:
    while(true){
      System.out.print(".");
      this.processUserMsgs();
    }
    另一种可能是在还没启动线程时就被阻塞了,最好检查下Client端有无flush()动作。
      

  3.   


    public class Snake {
    static int userCount=0; //连接用户数
    static List<User> userList=new ArrayList<User>(); //用户数组

    public static void main(String[] args) {

    try {

    ServerSocket ss = new ServerSocket(8585); //创建服务器端socket
    while(true){
    Socket socket = ss.accept(); //等待用户连接
    User user = new User(++Snake.userCount,socket); //连接用户并创建用户线程对象,分配连接id
    userList.add(user); //将用户线程对像添加到用户数组
    user.start(); //开始用户线程
    } } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }启动线程就这样的``应该和这个没关系``
      

  4.   


    不是判断,我是调试就进不去````另外客户端flush的时候是会中断到this.processUserMsgs();这条语句的```是在没有提交的时候进不去``````我遇到的情况是这样```我前面有两个提交进来了```之后没有提交,他就走不到this.processUserMsgs();这里了```
      

  5.   

    结贴了``找到原因了``是我没注意看api````inputStream.read()是会阻塞的``public int read(byte[] b)
             throws IOException
    从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数。在输入数据可用、检测到文件末尾或者抛出异常前,此方法一直阻塞。