Java tcp/udp

关于java TCP/UDP接收发送内容简单程序,首先运行服务端(接收者)然后运行客户端(发送者)

1、首先创建一个tcp服务端

public class TCPServer {

	public static void main(String[] args) {
		try {
			//创建服务器并指定端口
			ServerSocket ss = new ServerSocket(6666);
			//获取连接到服务端的socket对象
			Socket socket = ss.accept();
			//接收客户端发送内容
			byte[] buffer = new byte[1024];
			InputStream in = socket.getInputStream();
			int length = in.read(buffer);
			System.out.println(new String(buffer, 0, length));
			
			//返回客户端内容
			OutputStream out = socket.getOutputStream();
			out.write("连接成功".getBytes());
			
			//5、关闭资源
			in.close();
			out.close();
			socket.close();
//			ss.close(); //服务器通常不关闭
			
		} catch (Exception e) {
			e.printStackTrace();
		}
}

2、tcp客户端

public class TCPClient {

	public static void main(String[] args) {
		try {
			//1、创建socket对象
			Socket socket = new Socket("192.168.0.100", 6666);
			// 发送服务端
			OutputStream out = socket.getOutputStream();
			out.write("客户端发送给服务端".getBytes());
			
			//服务器返回信息
			InputStream in = socket.getInputStream();
			//获取流中数据
			byte[] buffer = new byte[1024];
			int length = in.read(buffer);
			//显示数据
			System.out.println(new String(buffer, 0, length));
			//4、关闭资源
			out.close();
			in.close();
			socket.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
}

 

 

UPP接收者

public class UDPReceive {

	public static void main(String[] args) {
		try {
			//1、创建datagramsocket接收端
			DatagramSocket ds = new DatagramSocket(12333);
			//2、创建datagrampacket接收
			byte[] buffer = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buffer, 1024);
			//3、将数据放到datagrampacket
			ds.receive(dp);
			//4、获取内容
			InetAddress address = dp.getAddress(); // 地址
			String ip = address.getHostAddress(); //ip地址
			int port = dp.getPort(); //端口
			byte[] data = dp.getData(); //内容
			
			//显示内容
			String content = new String(data, 0, data.length);
			System.out.println("地址:"+address+", ip:"+ip+", 端口:"+port+", 内容:"+content);
			
			//5、释放资源
			ds.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}

UDP发送者

public class UDPSend {
	
	public static void main(String[] args) {
		try {
			//1、创建datagramsocket发送端
			DatagramSocket ds = new DatagramSocket();
			//2、创建datagrampacket分装数据
			byte[] buffer = "hello world!".getBytes();
			DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
					InetAddress.getByName("192.168.0.100"), 12333);
			//3、发送数据
			ds.send(dp);
			//4、释放资源
			ds.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

 

你可能感兴趣的:(Java)