簡體   English   中英

Java中的多線程客戶端-服務器聊天應用程序

[英]Multi-Threading Client-Server Chat application in java

當我關閉客戶端時,它在服務器端給我錯誤

像:java.net.SocketException:連接重置在java.net.SocketInputStream.read(SocketInputStream.java:122)在java.net.SocketInputStream.read(SocketInputStream.java:122)在java.net.SocketInputStream.read(SocketInputStream) .java:210),位於HServer.run(HServer.java:28),位於java.io.DataInputStream.readLine(DataInputStream.java:513)

簽出代碼,請告訴我如何使用線程向所有其他客戶端發送一個客戶端消息,請幫幫我:)

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);
    }
}
}

嘗試這個:

構建強大的Java服務器

構建基本的Echo Server和ChatServer

我將此作為自己服務器的基礎。 它有點舊,並且沒有使用許多Java功能,但是效果很好。

花一些時間來理解它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM