简体   繁体   English

服务器通过Java中的套接字对选定客户端的响应

[英]Server response to selected client via socket in Java

I'm gonna create simple chat between 2 Android devices, in Java. 我将使用Java在2个Android设备之间创建简单的聊天。 I found simple script for server, but i'm new in programming sockets. 我发现了用于服务器的简单脚本,但是我是编程套接字的新手。

Problem: I want receive message from client A and send to client B. 问题:我想接收来自客户端A的消息并发送给客户端B。

I know how to create "echo" response to the same client, but how to send message to the other client? 我知道如何创建对同一客户端的“回声”响应,但是如何向其他客户端发送消息?

Now serwer look like this: 现在,服务看起来像这样:

              {
             String clientSentence;
             String capitalizedSentence;
             ServerSocket welcomeSocket = new ServerSocket(19198);
             Socket connectionSocket = welcomeSocket.accept();
             while(true)
             {

                BufferedReader inFromClient =
                   new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                clientSentence = inFromClient.readLine();
                System.out.println("Received: " + clientSentence);
                capitalizedSentence = clientSentence.toUpperCase() + '\n';
                outToClient.writeBytes(capitalizedSentence);
             }


          }

You need to keep track of your clients and their sockets/streams, and then you know where to send the message. 您需要跟踪客户端及其套接字/流,然后您知道将消息发送到哪里。 You also need to start a new thread for each client. 您还需要为每个客户端启动一个新线程。

You can find many examples if you google for Java chat server... 如果您通过Google搜索Java聊天服务器,则可以找到许多示例...

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

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