使用Java中的TCP连接向多个客户端广播

时间:2015-08-30 05:43:50

标签: java sockets tcp client-server

我正在尝试向多个客户端广播消息,但无法这样做。我尝试将套接字连接保存在数组列表中并使用for循环,我试图广播该消息,但只有发布消息的客户端才收到服务器的回复。

客户代码:

import java.net.*;
import java.util.Scanner;

import org.json.simple.JSONObject;

import java.io.*;

public class TCPClient {
public static void main (String args[]) {
  // arguments supply message and hostname
  JSONObject clientObj=new JSONObject();
Socket s = null;
try{
    int serverPort = 7899;
    Scanner scan=new Scanner(System.in);
    s = new Socket("127.0.0.1", serverPort);  
    System.out.println("Connection Established");
    DataInputStream in = new DataInputStream( s.getInputStream());
    DataOutputStream out =new DataOutputStream( s.getOutputStream());
    while(true)
    {
   System.out.print(">");
   String inputdata=scan.nextLine();
   clientObj.put("ID",inputdata );
   System.out.println("Sending data"); 
     out.writeUTF(clientObj.toString());     // UTF is a string encoding see Sn. 4.4
   String data = in.readUTF();   // read a line of data from the stream
   System.out.println(data) ;       //writing received data
   }
    }catch (UnknownHostException e) {
 System.out.println("Socket:"+e.getMessage());
 }catch (EOFException e){
 System.out.println("EOF:"+e.getMessage());
 }catch (IOException e){
 System.out.println("readline:"+e.getMessage());
 }finally {
 if(s!=null) try {
   s.close();
 }catch (IOException e){
   System.out.println("close:"+e.getMessage());
 }
  }
  }
}

服务器代码:

import java.net.*;
import java.util.ArrayList;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.*;

public class TCPServer {
static ArrayList<String> client=new ArrayList<String>();
static ArrayList<Socket> clientSock=new ArrayList<Socket>();
static int i = 0;
public static void main (String args[]) {
try{
  int serverPort = 7899; // the server port
  ServerSocket listenSocket = new ServerSocket(serverPort);
  while(true) {
    System.out.println("Server listening for a connection");
    Socket clientSocket = listenSocket.accept();
    i++;
    System.out.println("Received connection " + i );
    Connection c = new Connection(clientSocket);
    client.add("guest"+i);
    clientSock.add(clientSocket);
   }
 } 
 catch(IOException e) 
 {
   System.out.println("Listen socket:"+e.getMessage());
 }
 }
 public void display(String BroadMsg1)
 {
 for(int j=0;j<client.size();j++)
 {
    System.out.println(clientSock.get(j));
 }
 }
 public void broadcast(String BroadMsg)
 {
  String clientName=null;
  Socket cSock=null;
  //DataInputStream inBroad;
  DataOutputStream outBroad=null;
 for(int j=0;j<client.size();j++)
 {
    clientName=client.get(j);
    cSock=clientSock.get(j);
    try{
    outBroad=new DataOutputStream(cSock.getOutputStream());
    outBroad.writeUTF(clientName+">"+BroadMsg);
    }catch(Exception ex)
    {
        /*client.remove(j);
        clientSock.remove(j);*/
        System.out.println(ex.getMessage());
    }
    }
  }
  }

    class Connection extends Thread {
    TCPServer tcpser=new TCPServer();
  DataInputStream in;
  DataOutputStream out;
  Socket clientSocket;

  public Connection (Socket aClientSocket) {
  try {
   clientSocket = aClientSocket;
   in = new DataInputStream( clientSocket.getInputStream());
   out =new DataOutputStream( clientSocket.getOutputStream());
   this.start();
  } catch(IOException e) {
   System.out.println("Connection:"+e.getMessage());
  }
 }

 public void run(){

   JSONObject serObj=new JSONObject();
    JSONParser jParser=new JSONParser();
    try {           // an echo server
        while(true)
        {
 System.out.println("server reading data");
 String data = in.readUTF();        // read a line of data from the stream
  try {
    serObj=(JSONObject)jParser.parse(data);         //parsing JSONObject
   } catch (ParseException e) {
    e.printStackTrace();
    }
   System.out.println("server writing data");
  // tcpser.display(serObj.get("ID").toString());
  tcpser.broadcast(serObj.get("ID").toString());
 }}
 catch (EOFException e){
  System.out.println("EOF:"+e.getMessage());
 } catch(IOException e) {
  System.out.println("readline:"+e.getMessage());
 } finally{ 
 try {
   clientSocket.close();
 }catch (IOException e){/*close failed*/}
}
}
}

任何人都可以帮我解决这个错误。 在此先感谢:)

1 个答案:

答案 0 :(得分:1)

在服务器中使用accept命令创建Client Socket后,通过传递此socket is参数启动一个新的Thread。在新线程中,打开InputStream并处理它。

浏览所有客户端套接字的列表,并通过在相应的套接字上打开OutputStream来发送消息

请看一下这个例子Socket Programming。您可以查看java文档以获取替代方法Broadcasting

  

1)添加到列表后创建客户端线程。

     

2)在catch块中打印异常堆栈跟踪以了解异常。

     

3)替换cSock = clientSock.get(j);与迭代器一起通过所有插座。