网络通信--UDP和TCP

UDP和TCP的区别:

/**
*

  • @author dch

*/
//Udp客户端
public class UdpKHD {

public static void main(String[] args) throws Exception {
	
	//创建一个能发送的对象
	DatagramSocket ds = new DatagramSocket();
	//定义发送的话
	String string="wang";
	DatagramPacket dp = new DatagramPacket(string.getBytes(), string.length(), InetAddress.getByName("192.168.43.167"),8848);
	ds.send(dp);
	ds.close();
}

}
/**
*

  • @author dch

*/
//udp服务端
public class UdpFWD {

public static void main(String[] args) throws Exception {
	//创建接收的对象
	DatagramSocket ds = new DatagramSocket(8848);
	//定义一个字节数组
	byte [] b = new byte[1024];
	//这里是在打包?
	DatagramPacket dp = new DatagramPacket(b, 1024);
	//接收方法
	ds.receive(dp);
	//创建字符串对象
	String str1 = new String(dp.getData(), 0, dp.getLength());
	System.out.println(str1);
	ds.close();
}

}

TCP:
/**
*

  • @author dch

*/
//tcp客户端
public class TcpKHD {

public static void main(String[] args) throws Exception {
	
	Socket s = new Socket("192.168.43.167",7777);
	//先写
	OutputStream os = s.getOutputStream();
	//在读
	InputStream is = s.getInputStream();
	os.write("帅哥,我爱你".getBytes());
	byte [] b = new byte[1024];
	int len = is.read(b);
	System.out.println(new String(b,0,len));
	//释放资源
	s.close();
	
}

}

/**
*

  • @author dch

*/
//TCP服务端
public class TcpFWD {

public static void main(String[] args) throws Exception {
	
	//while(true){//创建对象
	ServerSocket ss = new ServerSocket(7777);
	//服务单接收
	Socket s = ss.accept();
	InputStream is = s.getInputStream();
	byte [] b = new byte[1024];
	int len = is.read(b);
	System.out.println(new String(b,0,len)+"收到了来自弟弟消息");
	OutputStream os = s.getOutputStream();
	os.write("弟弟,我知道了!".getBytes());
	s.close();
	ss.close();
	}
//}

}

猜你喜欢

转载自blog.csdn.net/qq_41035395/article/details/88987148