java网络测试
//Tcp
public class Test_IP_Client {
//接受服务器端的数据,并显现出来
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1", 8888);
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Test_IP_Server {
//拿到通信客户端的IP地址,返还给客户端
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
while (true){
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello" + s.getInetAddress() + " port:" + s.getPort());
dos.close();
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Udp
public class Test_Udp_1 {
//测试 UDP 通信 ,先收后打印
public static void main(String[] args) throws Exception {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
DatagramSocket ds = new DatagramSocket(5678);
while(true){
ds.receive(dp);
System.out.println(new String(buf, 0, dp.getLength()));
}
}
}
public class Test_Udp_2 {
//测试 UDP 通信,发数据
public static void main(String[] args) throws Exception {
byte[] buf = (new String("hello").getBytes()); //byte[] buf = "hell".getBytes(); 也可以
DatagramPacket dp = new DatagramPacket(buf, buf.length,new InetSocketAddress("127.0.0.1",5678));
DatagramSocket ds = new DatagramSocket(9999);
ds.send(dp);
ds.close();
}
}

浙公网安备 33010602011771号