我有一个UDP服务器和客户端,现在如何让他们不断发送/接收?

时间:2017-10-15 21:32:16

标签: java server udp client chat

正如简短的标题所说,我有一个UDP服务器和客户端。服务器目前有3种方法,一种用于打开套接字并接收数据包。下一个读取数据包并打印信息。最终从用户输入创建响应数据包。

我想在这里包含我的服务器代码,因为我认为如果我能够帮助您使服务器能够发送和接收我也可以将我的新知识转换为客户端!

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循环的方法,但是会有关于它的不同帖子。

1 个答案:

答案 0 :(得分:0)

首先,您必须: - 将createAndListen()拆分为两个方法:套接字必须只初始化一次,并且必须在receive()上循环。 - 然后重新制定你的代码和方法。

main 
    init socket     // only once
    while(some-condition)     // receive loop
        receive()   // this is a blocking method
        reply()     // and send()
    close socket
end

之后,您的代码会有一些重大改进,以使其更高效,更强大。查看Google有关Java套接字编程和良好实践的优质资料。