【发布时间】:2018-03-27 09:05:45
【问题描述】:
正如简短的标题所说,我有一个 UDP 服务器和客户端。服务器目前有 3 种方法,一种是打开套接字并接收数据包。 next 读取数据包并打印信息。最后根据用户输入创建一个响应包。
我将在此处包含我的服务器代码,因为我认为如果我可以在使服务器能够发送和接收方面获得帮助,我也可以将我的新知识转换到客户端!
import java.net.*;
import java.io.*;
public class ServerChat {
DatagramSocket Server = null;
byte[] buf = new byte[1024];
DatagramPacket incomingPacket = new DatagramPacket(buf, buf.length);
//Opens the socket to receive the packet
public void createAndListen() throws SocketException, IOException{
Server = new DatagramSocket(9876);
Server.receive(incomingPacket);
}
//Simply converts the packet to a string and then prints the message
public void read(){
String message = new String(incomingPacket.getData());
System.out.println("Client: " + message);
}
//This methhod will allow the user to print a message to be sent back to the client
public void send() throws IOException{
System.out.print("Server: ");
//Receiving input
BufferedReader response = new BufferedReader(new InputStreamReader(System.in));
String reply = response.readLine();
//Getting recipent information
InetAddress IPAddress = incomingPacket.getAddress();
int port = incomingPacket.getPort();
byte[] data = reply.getBytes();
//Crafting and sending the packet
DatagramPacket replyPacket = new DatagramPacket(data, data.length, IPAddress, port);
Server.send(replyPacket);
}
public static void main(String[] args) throws IOException {
ServerChat Server = new ServerChat();
Server.createAndListen();
Server.read();
Server.send();
}
感谢您的帮助! 快速编辑,因为重读似乎不清楚;服务器确实启动并监听,然后接收到客户端发送的数据包,并可以响应。在一次发送和接收之后,客户端和服务器都关闭了,这就是我试图阻止的,我希望它们保持打开状态以再次通信。我知道 UDP 不是连续连接,所以我认为我更需要服务器能够持续接收和发送数据包。
编辑 2:我重新编写了我的客户端以在端口上进行连续循环监听,它一次只能处理一条消息。现在我只需要它连续发送/接收!不过,当我从多种不同的方法更改为带有 while 循环的一种方法时,将对此发表不同的帖子。
【问题讨论】:
-
您需要发布您当前的代码。如果您在循环中接收并在循环中发送,则您必须获得连续的吞吐量。很明显你没有正确地做到这一点。
标签: java server udp client chat