JavaSE之TCP/UDP编程实现

TCP/UDP编程实现
UDP分为接收端和发送端:
接收端:

public class Test {
	public static void main(String[] args) throws IOException 
	{
		byte[] buf=new byte[1024];
		DatagramSocket ds = new DatagramSocket(8954);//定义一个DatagramSocket对象,端口号为8954
		DatagramPacket dp = new DatagramPacket(buf,1024);//用于接收数据
		System.out.println("等待接收数据");
		ds.receive(dp);//接收来自发送端的数据
		String str=new String(dp.getData(),0,dp.getLength())+"from"+
		dp.getAddress().getHostAddress()+":"+dp.getPort();
		System.out.println(str);
		ds.close();
	}
}

发送端:

public class Test1 {
	public static void main(String[] args) throws IOException
	{
		String str="zhou li liu";//要发送的数据
		DatagramSocket ds = new DatagramSocket();//定义一个DatagramSocket对象,端口号为8954
		DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),
				InetAddress.getByName("localhost"),8954);//用于发送数据
		System.out.println("发送数据");
		ds.send(dp);
		ds.close();
	}
}

TCP分为服务端和客户端:

服务端:

class TCPServer{
	public static final int PORT=7788;
	public void listen() throws IOException, InterruptedException {
		ServerSocket ss = new ServerSocket(PORT);//建立服务端与客户端之间的连接
		Socket cilent=ss.accept();//接收数据,返回一个Socket类型的cilent对象
		OutputStream os=cilent.getOutputStream();//获取输出流
		InputStream is=cilent.getInputStream();//获取输入流
		System.out.println("开始与客户端进行数据交互");
		os.write("华中科技大学欢迎你".getBytes());//向客户端所要发送的信息
		Thread.sleep(500);
		byte[] buf=new byte[1024];
		int len=is.read(buf);//读取客户端的信息
		System.out.println(new String(buf,0,len));//输出客户端的信息
		System.out.println("结束与客户端的交互");
		cilent.close();
		is.close();
		os.close();
	}
}
public class Test {
	public static void main(String[] args) throws IOException, InterruptedException 
	{
		new TCPServer().listen();
	}
}

客户端:

class TCPClient{
	public static final int PORT=7788;
	public void connect() throws UnknownHostException, IOException {
		Socket cilent= new Socket(InetAddress.getLocalHost(),PORT);//建立服务端与客户端之间的连接
	   java.io.InputStream is=cilent.getInputStream();//获取输入流
	    OutputStream os=cilent.getOutputStream();//获取输出流
	    os.write("让世界在我面前低头".getBytes());//向服务端所要发送的内容
		byte[] buf=new byte[1024];
		int len=is.read(buf);//读取服务端所发内容
		System.out.print(new String(buf,0,len));
		cilent.close();
		is.close();
		os.close();
	}	
}
public class Test1 {
	public static void main(String[] args) throws UnknownHostException, IOException 
	{
		new TCPClient().connect();
	}
}

你可能感兴趣的:(JavaSE之TCP/UDP编程实现)