2011-09-01 115 views
2

我在廣播每個客戶端發送的消息時遇到問題。服務器可以接收來自多個客戶端的每條消息,但不能廣播它。錯誤消息說,連接被拒絕 客戶:Java聊天系統

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

服務器:

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

}

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開始:

java.net.ConnectException: Connection refused: connect 

擴展輸出看起來像:

enter image description here

+0

_Error消息說,連接被拒絕客戶端:_你能不能給堆棧跟蹤? – Nivas

+0

https://imo.im/fd/A/gOeLB9QKrD/Untitled.png – jayp

+1

@jayp:請注意,從命令行復制/粘貼比包含相同的圖像更有用。你知道如何從Windows CLI複製嗎? –

回答

1

我根據有些困惑,爲什麼你試圖打開一個新的socket(你打算爲這個被髮送回客戶端?)從文件中讀取的字符串。也許

s = new Socket(strLine, 44441); 
prnt = new PrintWriter(s.getOutputStream(),true); 

應該是:

prnt = new PrintWriter(client.getOutputStream(),true); 

由於目前我沒有看到你在哪裏發送任何返回給客戶端。

編輯:確定你可以試試下面的:

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 */ } 
     } 
    } 
} 
+0

我忘了說,我有一個文件。它具有連接到服務器的客戶端的主機地址,並將套接字s連接到每個客戶端以廣播消息。如果我將它設置爲client.getOutputStream(),我認爲它會將消息發送給自己。 – jayp

+0

好吧,如果有防火牆,創建新客戶端連接可能會有問題。這可能是您看到連接拒絕錯誤的原因。相反,您會希望在接受連接時爲每個客戶端使用Socket對象。 – dbotha

+0

對不起,我只是一個初學者。 @。@我的客戶端只是在等待服務器發送內容。如果我沒有設置新的連接,那麼我只能將消息發送給發送者,而不是其他發送者。我很困惑。 @。@ – jayp