On the socket in java

TCP and UDP

TCP and UDP them are located in the transport layer in the OSI layered to provide support for application layer. TCP is a connection-oriented network transport protocols, client and server side need to establish a stable connection to transmit data to each other. The UDP is a connectionless transport protocol for the network, the client and the server does not need to establish a connection, the client sends out packets regardless of whether the other exists, it can be sent.

TCP

TCP ( Transmission Control Protocol ) transmission control protocol is a stable and reliable connection, the client and the server before establishing a connection requires three-way handshake . Although stable connection, but since the data transfer process is complicated, resulting in transmission efficiency than the UDP much lower. Typically require accurate data used in the scene, such as file transfer, web page display, message delivery and the like. In java the TCP by Socket和ServerSocketachieved two classes TCP function.

1.TCP client Socket
//客户端类
public class TestSocketclient {
	//构造方法
	public TestSocketclient(String ip,int port){
		try {
			@SuppressWarnings("resource")
			Socket socket = new Socket(ip,port);//指明服务器ip和端口号
			//向服务器发送消息
			String data = "hello server";
			OutputStream os = socket.getOutputStream();//输出流就是向服务器发送数据的流
			os.write(data.getBytes());
			
			//接收来自服务器的消息
			InputStream is = socket.getInputStream();//输入流就是接收来自服务器数据的流
			byte[] serverinfo = new byte[1024];
			int n = -1;
			while((n=is.read(serverinfo))!=-1){
				String string = new String(serverinfo,0,n);
				System.out.println(string);
			}
			
			os.close();
			is.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//启动方法,应该让服务器端先启动
	public static void main(String[] args) {
		try {
			new TestSocketclient(InetAddress.getLocalHost().getHostAddress(),8888);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
}
2.TCP server ServerSocket
//服务器端
public class TestServerSocket {
	//构造方法
	public TestServerSocket(int port){
		try {
			ServerSocket ss = new ServerSocket(port);//监听端口
			//接收来自客户端的数据,该方法accept()是阻塞方法,直到接到请求才往下执行。
			Socket accept = ss.accept();
			InputStream is = accept.getInputStream();
			byte[] packet = new byte[1024];
			int n = is.read(packet);
			String string = new String(packet,0,n);
			System.out.println(string);
			//向客户端发送消息
			OutputStream os = accept.getOutputStream();
			os.write("hello client".getBytes());
			
			os.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//启动方法
	public static void main(String[] args) {
		new TestServerSocket(8888);
	}
}

UDP

UDP ( the User Datagram Protocol ) user datagram protocol is a less stable data transmission protocol, they often lose packets during transmission, but without losing too much, do not affect the overall integrity of the data. Looks UDP since instability, but also loss of data, why remain today, has not been abandoned? That is because it has a very extraordinary transfer efficiency. Is also widely used, such as online games, although not all the data is UDP (such as the player attributes) but a large proportion of its components, QQ chat tools, real-time video calls, video conferencing, etc. Using the java DatagramSocketimplementation class UDP function.

1.UDP client
//客户端
public class TestUDPclient {
	//构造方法
	public TestUDPclient(String ip,int port){
		
		try {
			//客户端不用在socket上指明ip和port
			DatagramSocket ds = new DatagramSocket();
			
			byte[] buf = "nihao 服务器".getBytes();
			int length = buf.length-4;//必须是绑定数据的大小,不能大于,可以小于,不能为负
			InetAddress address = InetAddress.getByName(ip);
			//在数据报上指明服务器的ip和port
			DatagramPacket dp = new DatagramPacket(buf,length, address, port);
			//发送数据
			ds.send(dp);
			//关闭套接字
			ds.close();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//启动方法
	public static void main(String[] args) {
		new TestUDPclient("localhost",7777);
	}
}
2.UDP server
//服务器端
public class TestUDPServer {
	//构造方法
	public TestUDPServer(int port){
		try {
			
			DatagramSocket ps = new DatagramSocket(port);//监听port端口是否有请求
			byte[] b= new byte[1024];
			DatagramPacket pd = new DatagramPacket(b, 1024);//准备一个空包接收数据用
			//接收数据
			ps.receive(pd);
			//得到数据并打印
			byte[] data = pd.getData();
			System.out.println(new String(data,0,data.length));
			//关闭套接字
			ps.close();
		} catch (Exception e) {
		}
	}
	//启动方法
	public static void main(String[] args) {
		new TestUDPServer(7777);
	}

}
3. Supplement

UDP in use DatagramSocketwhen the class implements the client and server are using the same class, they are distinguished by the server and the client whether configure the port number and IP. As long as the configuration of the port and IP DatagramSocket can act as a server. But the same IP address as the lower end of the slogan can not, or will report the port occupied by the anomaly. 谁先接收数据谁先启动The following are illustrative:

  • Client
public class TestUDPclient {
	
	public TestUDPclient(String ip,int port){
		
		try {
			//作为端口号为8888的服务器端
			DatagramSocket ds = new DatagramSocket(8888);
			
			byte[] buf = "nihao 服务器".getBytes();
			int length = buf.length;
			InetAddress address = InetAddress.getByName(ip);
			DatagramPacket dp = new DatagramPacket(buf,length, address, port);
			
			ds.send(dp);
			//发送后再来接收数据
			DatagramPacket dp2 = new DatagramPacket(new byte[1024], 1024);
			ds.receive(dp2);
			byte[] data = dp2.getData();
			System.out.println(new String(data,0,data.length));
			
			ds.close();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new TestUDPclient("localhost",7777);
	}
}
  • Service-Terminal
public class TestUDPServer {
	
	public TestUDPServer(int port){
		try {
			//作为端口号为7777的服务器端
			DatagramSocket ps = new DatagramSocket(port);
			byte[] b= new byte[1024];
			DatagramPacket pd = new DatagramPacket(b, 1024);
			
			ps.receive(pd);
			
			byte[] data = pd.getData();
			System.out.println(new String(data,0,data.length));
			//接收完数据再发送,发送给本地端口号为8888的服务器端
			DatagramPacket dp2 = new DatagramPacket("nihao".getBytes(),5,InetAddress.getByName("localhost"),8888);
			ps.send(dp2);
			
			ps.close();
		} catch (Exception e) {
		}
	}
	
	public static void main(String[] args) {
		new TestUDPServer(7777);
	}

}
Released six original articles · won praise 2 · Views 510

Guess you like

Origin blog.csdn.net/wl12346/article/details/104840355