简体   繁体   English

通过Java中的套接字发送数据

[英]Sending data through sockets in java

I am currently working on a one server many clients system. 我目前正在使用一台服务器的多客户端系统。 I am trying to get it so the server can send out one command, through a PrintWriter, that will go through to all of the clients connected on that socket. 我正在尝试获取它,以便服务器可以通过PrintWriter发送一个命令,该命令将传递给该套接字上连接的所有客户端。 However in practice the command only goes through to one client. 但是实际上,该命令仅传递给一个客户端。 All of the clients are created on one socket, and all use the same Scanner. 所有客户端都在一个套接字上创建,并且都使用相同的扫描仪。 Is what I am trying to do possible? 我想做的事可能吗?

Some code(incase it helps) 一些代码(以防万一)

Creation of the socket: 创建套接字:

serverSocketRefresh = new ServerSocket(PORTREFRESH);
refresh = serverSocketRefresh.accept();
Creation of the Print Writer and the Scanner:

networkOutputRefresh = new PrintWriter(refresh.getOutputStream(), true);
networkInput = new Scanner(refresh.getInputStream());

Ceation of the clients: 客户的赞誉:

do
{
    // Wait for client...

    client = serverSocket.accept();
    System.out.println("\nNew client accepted.\n");
    handler = new ClientHandler(client,networkOutputRefresh, itemArray, bidderArray);
    handler.start();
} while (true);

The command im trying to transmit to all of the clients: 该命令正在尝试传输给所有客户端:

public static void updatePrice()
{   
    networkOutputRefresh.println("1");
}

Why not just use a BufferedReader and BufferedWriter, and make a new one each time you accept a client? 为什么不只使用BufferedReader和BufferedWriter,并在每次接受客户端时创建一个新的?

Edit: Or, if that '1' is the only thing you will ever send over that socket, just send it over the socket directly, as a byte. 编辑:或者,如果“ 1”是您将要通过该套接字发送的唯一内容,则直接将其作为字节直接通过套接字发送。 I believe the method is something like socket.write(new byte[] { 1 }, 0, 1) , and to read on the other end, socket.read(buffer, 0, 1) , where buffer is a byte array of length 1. 我相信该方法类似于socket.write(new byte[] { 1 }, 0, 1) ,并且要在另一端读取socket.read(buffer, 0, 1) ,其中buffer是一个字节数组长度1。

I am not sure if I correctly understand your code but it seems you are using a single reference of client. 我不确定我是否正确理解您的代码,但似乎您使用的是客户端的单个引用。 And your client reference will be holding the last client reference and hence the printwrite is writing only for that client. 而且您的客户参考将保存最后一个客户参考,因此printwrite仅为该客户编写。 Ideally if you want to publish something to all the clients then you should have a collection of client references.Whenever you get an accept on the server socket, add the new client reference to your collection. 理想情况下,如果要向所有客户端发布内容,则应具有客户端引用的集合。只要在服务器套接字上接受,就将新的客户端引用添加到集合中。 And whenever you have to publish to all the clients just iterate over your client collection and publish using their associated printwriters. 而且,每当您需要发布给所有客户时,只需遍历您的客户集合并使用其关联的印刷机即可发布。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM