利用TCP实现消息传送

//客户端

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Test01 {
	// 客户端
	public static void main(String[] args) throws Exception {

		// 插头
		DatagramSocket socket = new DatagramSocket();
		// 传入数据
		String str = "xtcyvubi";
		// 要转换成数组
		byte[] m = str.getBytes();
		int len = m.length;
		int port = 10088;
		// 地址
		InetAddress address = InetAddress.getLocalHost();
		// 数据包DatagramPacket
		DatagramPacket sendPacket = new DatagramPacket(m, len, address, port);
		// 利用插头打包发送
		socket.send(sendPacket);
		// 关闭资源
		socket.close();
	}

}

//服务端

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Test001 {
//服务端:接受客服端里面的数据
	public static void main(String[] args) throws Exception {
//有端口的插头
		int port=10088;
	   DatagramSocket socket =new DatagramSocket(port);
	     byte[] buf=new byte[1024];
	   int length = buf.length;
	   DatagramPacket sendPacket=new DatagramPacket(buf, length);
	   //接收数据包
	   socket.receive(sendPacket);
	   
	   //拆包
	   byte[] data = sendPacket.getData();
	   //for循环遍历出来
	   for(int i=0;i<length;i++) {
		   System.err.println(data[i]);
	   }
	   //关闭资源
	   socket.close();
	}

}

你可能感兴趣的:(TCP和UDP的用法,java)