首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java聊天系统

Java聊天系统
EN

Stack Overflow用户
提问于 2011-09-01 11:24:02
回答 1查看 1.1K关注 0票数 2

我在广播每个客户发送的信息方面有问题。服务器可以接收来自多个客户端的每条消息,但不能广播它。错误消息显示,拒绝连接的客户端:

代码语言:javascript
运行
复制
    public void initializeConnection(){
    try {
        host = InetAddress.getLocalHost();
        try{
              // Create file 
              FileWriter fstream = new FileWriter("src/out.txt", true);
              BufferedWriter out = new BufferedWriter(fstream);
              out.write(host.getHostAddress()+'\n');
              //Close the output stream
              out.close();
          }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
          }
        clientSocket = new Socket(host.getHostAddress(), port);
        outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
        inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

    }
    catch(IOException ioEx) {
        ioEx.printStackTrace();
    } 
}

public void actionPerformed(ActionEvent e)
{
    if(e.getSource()==quit){
        try {
            outToServer.close();
            clientSocket.close();
            System.exit(1);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    else if(e.getSource()==button){ 
        if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
            String message = outMsgArea.getText();
            outToServer.println(clientName+": "+message);
            outMsgArea.setText("");
        }
    }
}

public void run(){
    try {
        while(true){
            String message = inFromServer.readLine();
            System.out.println(message);
                inMsgArea.append(message+'\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

服务器:

代码语言:javascript
运行
复制
import java.io.*;
import java.net.*;
import java.util.*;

public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
  try{
    server = new ServerSocket(port);
  } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
  }
  while(true){
    ClientWorker w;
    try{
//server.accept returns a client connection
      w = new ClientWorker(server.accept());
      Thread t = new Thread(w);
      t.start();
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
  }
}

protected void finalize(){
    //Objects created in run method are finalized when
    //program terminates and thread exits
         try{
            server.close();
        } catch (IOException e) {
            System.out.println("Could not close socket");
            System.exit(-1);
        }
      }

public static void main(String[] args) {
    new RelayChatServer().listenSocket();
}

}

代码语言:javascript
运行
复制
class ClientWorker implements Runnable {
  private Socket client;

//Constructor
  ClientWorker(Socket client) {
    this.client = client;
  }

  public void run(){
    String line;
BufferedReader in = null;
PrintWriter out = null;
try{
  in = new BufferedReader(new 
    InputStreamReader(client.getInputStream()));
  //out = new 
  //  PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
  System.out.println("in or out failed");
  System.exit(-1);
}

while(true){
  try{
    line = in.readLine();
//Send data back to client
    //out.println(line);
//Append data to text area
    if(line!=null && line!=""){
        System.out.println(line);
    try{
          // Open the file that is the first 
          // command line parameter
          FileInputStream fstream = new FileInputStream("out.txt");
          BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
          String strLine;
          //Read File Line By Line
          Socket s;
          PrintWriter prnt;
          while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "")   {
          // Print the content on the console
              s = new Socket(strLine, 44441);
              prnt = new PrintWriter(s.getOutputStream(),true);
              prnt.println(line);
              System.out.println(strLine);
              prnt.close();
              s.close();
          }
          //Close the input stream
          //inp.close();
            }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
          }
    }
   }catch (IOException e) {
    System.out.println("Read failed");
    e.printStackTrace();
    System.exit(-1);
   }
}
  }

}

Exception启动:

代码语言:javascript
运行
复制
java.net.ConnectException: Connection refused: connect

扩展后的输出如下:

EN

回答 1

Stack Overflow用户

发布于 2011-09-01 11:34:49

我有点困惑为什么要打开一个新的套接字(您打算将这个套接字发送回客户机吗?)基于从文件中读取的字符串。也许吧

代码语言:javascript
运行
复制
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);

应:

代码语言:javascript
运行
复制
prnt = new PrintWriter(client.getOutputStream(),true);

目前,我看不出你要把什么东西送回客户。

编辑:好的,尝试如下所示:

代码语言:javascript
运行
复制
static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {

    private Socket socket;
    private PrintWriter writer;

    ClientWorker(Socket socket) {
        this.socket = socket;
        try {
            this.writer = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException ex) { /* do something sensible */ }
    }

    public void run() {
        synchronized(connectedClients) {
            connectedClients.add(this);
        }

        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException e) { /* do something sensible */ }

        while (true) {
            try {
                String line = in.readLine();
                if (line != null && line != "") {
                    synchronized (connectedClients) {
                        for (int i = 0; i < connectedClients.size(); ++i){
                            ClientWorker client = connectedClients.get(i);
                            client.writer.println(line);
                        }
                    }
                }
            } catch (IOException e) { /* do something sensible */ }
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7269607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档