Java language foundation (100)-network programming (udp tcp sending and receiving data)

We know that in a computer network, each host has a unique identifier, which we call an IP address. Only with the IP address of a certain host can it communicate with it. So when it comes to network programming, we must use InetAddress class, the class provides host name resolution method for IP address (or vice versa), allowing us to determine a host. Its usage is simple, we will not talk about it separately, please refer to http://tool.oschina.net/uploads/apidocs/jdk-zh/java/net/InetAddress.html


UDP protocol to send and receive data (DatagramSocket)

UDP send data demo:

package netDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class udpSendDemo {

	/**
	 * UDP发送数据编程步骤
	 * 1 创建对象
	 * 2 封装数据
	 * 3 发送数据
	 * 4 回收资源
	 * 
	 * udp协议发送接收数据被封装在  DatagramSocket 类中
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		 
         // 创建对象
		 DatagramSocket ds = new DatagramSocket();
		 
		 // 键盘录入
		 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		 String line = null;
		 
		 while((line=br.readLine())!=null){
			 if("exit".equals(line)){
				 break;
			 }
			 // 封装数据包 
			 //DatagramPacket(byte[] buf, int length, InetAddress address, int port)
			 byte[] by = line.getBytes();
			 DatagramPacket dp = new DatagramPacket(
					 by,by.length,
					 InetAddress.getByName("192.168.1.255"),8888);
			 
			 // 发送数据 send(DatagramPacket p)
			  ds.send(dp);
		 }
		   
		 // 回收资源
		 ds.close();
	}

}


UDP receive data demo:

package netDemo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
 
public class udpReceiveDemo {

	/**
	 * UDP接收数据编程步骤
	 * 1 创建接收端socket对象
	 * 2 创建数据包作为接收容器
	 * 3 接收数据
	 * 4 处理数据显示数据
	 * 5 释放资源 
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// 创建接收对象
		DatagramSocket ds = new DatagramSocket(8888); 
		
		// 创建数据包
		byte[] by = new byte[1024];
		int len = by.length;
		DatagramPacket dp = new DatagramPacket(by,len);
		
		while(true){
			// 接收数据包
			ds.receive(dp);
			
			// 处理数据包并显示
			byte[] by2 = dp.getData();
			int length = dp.getLength();
			String s = new String(by2,0,length);
			
			String ip = dp.getAddress().getHostAddress();
			System.out.println(ip +":"+s);
		}
		
		
		// 释放资源 服务器端应该总是开启状态 所以用不到资源回收
    //		ds.close();
	}

}


Multithreading to achieve the same window (chat room) both sending and receiving data:

Send thread:

package netDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class SendThread implements Runnable {
    private DatagramSocket ds;
	public SendThread(DatagramSocket ds) {
		 this.ds = ds;
	}

	@Override
	public void run() {
		 // 键盘录入
		 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		 String line = null;
		 
		 try {
			while((line=br.readLine())!=null){
				 if("exit".equals(line)){
					 break;
				 }
				 // 封装数据包 
				 //DatagramPacket(byte[] buf, int length, InetAddress address, int port)
				 byte[] by = line.getBytes();
				 DatagramPacket dp = new DatagramPacket(
						 by,by.length,
						 InetAddress.getByName("192.168.1.255"),8888);
				 
				 // 发送数据 send(DatagramPacket p)
				  ds.send(dp);
			 }
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			// 回收资源
			 ds.close();
		}
		   
	}

}


Receiving thread:

package netDemo;

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

public class ReceiveThread implements Runnable {
	 private DatagramSocket ds;
    public ReceiveThread(DatagramSocket ds){
    	this.ds = ds;
    }
	@Override
	public void run() {
		// 创建数据包
		byte[] by = new byte[1024];
		int len = by.length;
		DatagramPacket dp = new DatagramPacket(by,len);
		
		while(true){
			// 接收数据包
			try {
				ds.receive(dp);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// 处理数据包并显示
			byte[] by2 = dp.getData();
			int length = dp.getLength();
			String s = new String(by2,0,length);
			
			String ip = dp.getAddress().getHostAddress();
			System.out.println(ip +":"+s);
		}

	}

}


Chat room (send and receive messages in the same window):

package netDemo;

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

public class ChatRoom {
 
	public static void main(String[] args) throws SocketException {
		 
		SendThread st = new SendThread(new DatagramSocket());
		ReceiveThread rt = new ReceiveThread(new DatagramSocket(8888));

		Thread t1 = new Thread(st);
		Thread t2 = new Thread(rt);
		
		t1.start();
		t2.start();
	}

}


TCP protocol to send and receive data (Socket)

TCP send demo (client):

package netDemo;


import java.io.IOException;
import java.io.InputStream;

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

public class TcpClientDemo {

	public static void main(String[] args) throws UnknownHostException, IOException {
		 // 创建Socket对象
		 Socket s = new Socket("192.168.1.106",9999);
		 // 获得输出流对象
         OutputStream os = s.getOutputStream();
         // 给服务器发数据
         
         os.write("hello tcp".getBytes());
        
         // 得到输入流对象
         InputStream is = s.getInputStream();
         
         // 接收服务端的返回消息
          byte[] bys = new byte[1024];
          int len = is.read(bys);
          String str = new String(bys,0,len);
          System.out.println(str);
          
         // 释放资源
         s.close();
	}

}


TCP receiving demo (server):

package netDemo;

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

 /**
  * 1 创建服务端Socket对象
  * 2 监听客户端连接
  * 3 获得输入流对象
  * 4 读取数据并处理
  */
 
public class TcpServerDemo {
 
	public static void main(String[] args) throws IOException {
		 // 创建服务端Socket对象
		 ServerSocket ss = new ServerSocket(9999);
		 // 监听客户端连接
		 Socket s = ss.accept();
		 // 得到输入流对象 读取数据
		 InputStream is = s.getInputStream();
		 byte[] b = new byte[1024];
		 int len = is.read(b);
         String str = new String(b,0,len);
         System.out.println(str);
         // 得到输出流对象 
         OutputStream os = s.getOutputStream();
         // 给客户端返回状态
         os.write("发送成功".getBytes());
         s.close();
	}

}

Using the above demo flexibly, we can achieve many functions. For example, the client reads the content from the file, and the server saves the received content in the file, and we can upload the file. Using multi-threading on the server side, we can realize that multiple clients upload at the same time without affecting each other.



Guess you like

Origin blog.csdn.net/wang740209668/article/details/78209006