Java中的UDP聊天
我正在尝试使用UDP创建一个客户端和服务器聊天程序。我遵循了一个使用TCP制作类似程序的教程,然后尝试将我的知识转换为使用UDP以类似的方式制作一个程序 我已经完成了一个客户端和服务器端,两者都没有显示错误,将运行,但一旦运行,将不会向另一方发送消息或接收消息。。。有人能帮我看看我做错了什么吗 用于发送消息的服务器端:Java中的UDP聊天,java,sockets,udp,chat,Java,Sockets,Udp,Chat,我正在尝试使用UDP创建一个客户端和服务器聊天程序。我遵循了一个使用TCP制作类似程序的教程,然后尝试将我的知识转换为使用UDP以类似的方式制作一个程序 我已经完成了一个客户端和服务器端,两者都没有显示错误,将运行,但一旦运行,将不会向另一方发送消息或接收消息。。。有人能帮我看看我做错了什么吗 用于发送消息的服务器端: try{ //creates the packet to be sent byte[] buf = new byte[256];
try{
//creates the packet to be sent
byte[] buf = new byte[256];
String msgout = serverText.getText().trim();
buf = msgout.getBytes();
//uses the socet.receive method to get the packet to retrieve information to send
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ss.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
//uses packet information to create and send packet
DatagramPacket packetSend = new DatagramPacket(buf, buf.length, address, port);
ss.send(packetSend);
//Displays the message in the chat area and clears the text area
serverArea.setText(serverArea.getText().trim()+"\n Server: "+msgout);
serverText.setText("");
}catch (Exception e){
}
然后是设置插座和接收/打印的主屏幕:
String msgin = "";
try{
ss = new DatagramSocket(1420); // Sets socket at 1420
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ss.receive(packet); //Receives the packet from the socket
//Converts the byte array into a string
String clientMsg = new String(packet.getData(), 0, packet.getLength());
while(!msgin.equals("exit")){
//Displays the message
msgin = clientMsg;
serverArea.setText(serverArea.getText().trim()+"\n Client: "+msgin); //displays client message
}
}catch(Exception e){
}
这是客户端代码,我将其发送和接收区域合并为一个块:
try{
//Creates the message out using the known socket that the Server creates and the known local address
String msgout = clientText.getText().trim();
sendBuf = msgout.getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket sp = new DatagramPacket(sendBuf, sendBuf.length, address, 1420);
s.send(sp);
//Displays the text and clears the text field
clientchat.setText(clientchat.getText().trim()+"\n Server: "+msgout);
clientText.setText("");
}catch (Exception e){
}
String msgin = "";
try{
//Creates a socket
DatagramSocket s = new DatagramSocket();
//Receives the message from the server
byte[] buf = new byte[256];
DatagramPacket rp = new DatagramPacket(buf, buf.length);
s.receive(rp);
//Converts byte array to message
String clientMsg = new String(rp.getData(), 0, rp.getLength());
while(!msgin.equals("exit")){
//Displays the message
msgin = clientMsg;
clientchat.setText(clientchat.getText().trim()+"\n Server: "+msgin); //displays client message
}
}catch (Exception e){
}
任何帮助和提示都将不胜感激 如果没有发生任何事情,并且您无法发送/接收消息,则可能会生成异常 然而,由于您有一个try-catch块,它捕获所有异常,然后什么也不做,所以您将不知道抛出了什么异常,如果抛出了任何异常的话 与其简单地忽略异常,您至少应该打印它们的原因 在catch语句中,添加以下内容,您将能够更轻松地进行调试
e.printStackTrace();
如果您有空的catch块,当然不会看到错误。不幸的是,这对我的程序没有任何作用,它仍然没有任何作用。我想我只能放弃它,试着从新开始。