Java中的多线程客户端 - 服务器聊天应用程序

时间:2015-01-07 15:46:43

标签: java multithreading sockets

当我关闭客户端时,它在服务器端给出了错误

  

like:java.net.SocketException:Connection reset at at   java.net.SocketInputStream.read(SocketInputStream.java:196)at   java.net.SocketInputStream.read(SocketInputStream.java:122)at   java.net.SocketInputStream.read(SocketInputStream.java:210)at   java.io.DataInputStream.readLine(DataInputStream.java:513)at   HServer.run(HServer.java:28)

检查代码,请告诉我如何使用线程向所有其他客户端发送一条客户端消息,请帮助我们:)

ClientDemo.java

import java.io.*;
import java.net.Socket;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author zain-mughal
*/
public class ClientDemo extends javax.swing.JFrame {
DataInputStream input;
PrintWriter output;
public void Connect(){
    try {
        Socket s = new Socket("127.0.0.1", 2111);
        input=new DataInputStream(s.getInputStream());
        output=new PrintWriter(s.getOutputStream());
        boolean more_data=true;
        while(more_data){
            String in=input.readLine();
            if(in==null){
                more_data=false;
            }
            else{
                System.out.println(in);
            }
        }
        s.close();
        input.close();
        output.close();
    } catch (Exception ex) {
       ex.printStackTrace();
    }
}
public static void main(String args[]){
   ClientDemo obj=new ClientDemo();
   obj.Connect();

}

}

HServer.java

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author zain-mughal
*/
public class HServer extends Thread {
Socket AcceptReQ;
public HServer(Socket reqAccept) {
    this.AcceptReQ=reqAccept;
}
@Override
public void run(){
    try {
        DataInputStream input = new DataInputStream(AcceptReQ.getInputStream());
        PrintWriter output = new PrintWriter(AcceptReQ.getOutputStream());
        String in=null;
        while((in=input.readLine())!=null){
                System.out.println(in);
        }

        AcceptReQ.close();
        input.close();
        output.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
  }
 public static void main(String args[]){
    try {
        ServerSocket req = new ServerSocket(2111);

        while(true){
            Socket reqAccept=req.accept();
            Thread t=new HServer(reqAccept);
            t.start();
        }
    } catch (Exception ex) {
        Logger.getLogger(HServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

1 个答案:

答案 0 :(得分:0)

试试这个:

Build a robust Java server

Building a basic Echo Server and A ChatServer

我用它作为我自己服务器的基础。 它有点旧,并且没有使用许多Java功能,但效果很好。

花一些时间来理解它。