TCP UDP 经典 4个小例子 实现代码

TCP:


1.TCP服务端:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
	public static void main(String[] args) {
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(5000);// 创建TCP连接
			
			Socket s = ss.accept();// 阻塞接收client
			
			InputStream is = s.getInputStream();// 提取输入流

			byte[] buf = new byte[1024];

			is.read(buf, 0, buf.length); // 将输入流的信息读出到buf

			String mes = new String(buf);
			System.out.println(mes);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ss != null) {
					ss.close();// 用完就关闭
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

2.TCP客户端:

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient {
	public static void main(String[] args) {
		Socket s = null;
		try {
			s = new Socket("127.0.0.1", 5000);// 创建TCP连接

			OutputStream os = s.getOutputStream();// 从中获取输出流

			os.write("你好".getBytes());// 输出信息

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (s != null) {// 用完就关闭
					s.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}




~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

UDP


3.UDP服务端

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


public class UDPServer {
	public static void main(String[] args) {
		DatagramSocket ds = null;
		
		try {
			ds = new DatagramSocket(5000);  //创建UDP连接
			
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf,buf.length); //将数据拆包到buf
			
			ds.receive(dp); //阻塞接收client发过来的数据包
			
			String mes =  new String(buf);
			
			System.out.println(mes);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(ds !=null) {
				ds.close(); //关闭
			}
		}
	}
}


4.UDP客户端:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UDPClient {
	public static void main(String[] args) {
		DatagramSocket ds = null;
		try {
			ds = new DatagramSocket(); //创建UDP连接

			byte[] buf = "你好么".getBytes();

			DatagramPacket dp = new DatagramPacket(buf, buf.length,
					new InetSocketAddress("127.0.0.1", 5000)); //将数据打好包,并指定数据包 送到哪里

			ds.send(dp);//将数据报包发送
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			ds.close();//关闭
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值