简体   繁体   English

在Java中使用TCP聊天

[英]Chat using TCP in Java

I am making a chat in Java which uses a TCP protocol. 我正在使用TCP协议的Java中聊天。 I have a client and a server side. 我有一个客户端和一个服务器端。

To send a message to another user, I have to send the message to the server through my client, and the server has to send it to another client. 要发送消息给另一个用户,我必须通过客户端将消息发送给服务器,而服务器必须将消息发送给另一个客户端。

The server holds the addresses of both online users. 服务器保存两个在线用户的地址。 When I send a private message, the server finds the ip and a port and creates a socket from them. 当我发送私人消息时,服务器会找到ip和端口,并从中创建套接字。 The problem is that it doesn't work correctly. 问题在于它无法正常工作。

Here's the code: 这是代码:

int portNumber = 4444;
String host = "192.168.0.100”;
Socket link;
try {
    link = new Socket(host, portNumber);
    // Then I set to already created PrintWriter the outputstream
    out = new PrintWriter(link.getOutputStream(), true);
} catch (Exception e) {}
// Unfortunately the server freezes here (it doesn't show anything).

How to solve this problem? 如何解决这个问题呢? Where dod I make a mistake? 我在哪里犯错? Thank you in advance. 先感谢您。

You shouldn't create a new Socket to send a message. 您不应该创建新的Socket来发送消息。 Instead, use a socket of an existing connection. 而是使用现有连接的套接字。

The sequence should be the following: 顺序应如下:

  1. Client A connects to the server (server stores the connection as SocketA). 客户端A连接到服务器(服务器将连接存储为SocketA)。
  2. Client B connects to the server (server stores the connection as SocketB). 客户端B连接到服务器(服务器将连接存储为SocketB)。
  3. Server reads a private message from SocketA. 服务器从SocketA读取私人消息。 The message is addressed to client B. 该消息已发送给客户端B。
  4. Server finds the existing socket for client B. It's SocketB. 服务器找到客户端B的现有套接字。它是SocketB。
  5. Server sends the message into SocketB. 服务器将消息发送到SocketB。

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

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