使用Java中的TCP连接广播到多个客户端 [英] Broadcasting to multiple clients using TCP connection in Java

查看:208
本文介绍了使用Java中的TCP连接广播到多个客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to broadcast a message to multiple clients but could not do so. I tried saving the socket connections in an array list and using a for loop, i tried to broadcast the message but only the client who posted the message is receiving the reply from server.

客户代码:

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



代码:

Server Code:

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

任何人都可以帮助我纠正错误。
提前感谢:)

Can anyone please help me out to rectify the mistake. Thanks in advance :)

推荐答案

在服务器中使用accept命令创建Client Socket之后,通过传递这个套接字是参数。在新线程中,打开InputStream并处理它。

After creating Client Socket with accept command in server, start a new Thread by passing this socket is parameter. In the new thread, open InputStream and process it.

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

Go through the list of all client sockets and send the message by opening OutputStream on respective socket

查看此示例套接字编程。您可以查看java文档的替代方法广播

Have look at this example Socket Programming. You can look at java docs for alternative approach Broadcasting


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

1) Create client thread after adding to the list.

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

2)Print Exception stack trace in catch block to know exception.

3)替换cSock = clientSock。 get(j); Iterator可以通过所有套接字。

3) replace cSock=clientSock.get(j); with Iterator to go through all sockets.

这篇关于使用Java中的TCP连接广播到多个客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆