客户端不能将接收到信息完全打印出来,请问是怎么回事呢?(客户端显示在代码后)
/* *UDP服务端 */
package com.imooc;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPserver {
UDPserver() throws IOException{
DatagramSocket ds = new DatagramSocket(5555);
byte[] b = new byte[2048];
DatagramPacket dp = new DatagramPacket(b,0,b.length);
ds.receive(dp);
String s = new String(b);
System.out.println("我是服务器,客户端说: "+s);
InetAddress address = InetAddress.getByName("localhost");
int port = dp.getPort();
byte[] b1 = new byte[2048];
b1= "客户端你好,你的信息已经收到,我是服务器".getBytes();
DatagramPacket dp2 = new DatagramPacket(b1,0,b1.length,address,port);
ds.send(dp2);
ds.close();
}
public static void main(String[] args) throws IOException {
UDPserver us = new UDPserver();
}
}
/*
*UDP客户端
*/
package com.imooc;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPclient {
public static void main(String[] args) throws IOException{
DatagramSocket ds = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
int port = 5555;
byte[] b = new byte[2048];
b ="用户名:1;密码:2".getBytes();
DatagramPacket dp = new DatagramPacket(b,b.length,address,port);
ds.send(dp);
DatagramPacket dp1 = new DatagramPacket(b,b.length);
ds.receive(dp1);
String s1 = new String(b);
System.out.println("我是客户端,服务器说: "+s1);
ds.close();
}
}
客户端打印:
客户端你好,你?