cool hit counter J2SE Fast Forward] - Introduction to Socket Programming (TCP/UDP)_Intefrankly

J2SE Fast Forward] - Introduction to Socket Programming (TCP/UDP)


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/44645323

At the time of the exhibition, the main function of our work "Super Fly Chat" was chatting, including LAN chatting, extranet chatting, etc. Although it was implemented in VB (winsock control) at that time, the ideas in each kind of programming were still similar, so when I learned socket programming in Java, I felt very close to it.

Conceptual understanding

Sockets, also known as "sockets", are used to make requests to hosts on the network or to answer requests made on the network.

Let's start the article with a brief look at the two protocols, TCP and UDP.

TCP

TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte-stream-based communication protocol located at the transport layer. Of these three features, connection-oriented is like a phone call, where both sides of the phone must remain connected in order to talk; reliable is like video on QQ, where one side sends a video request and the other side must agree before a video connection can be established, and arguably secure; and byte-stream based, just keep reading below.

The most important idea of the TCP is the famous "three handshakes".

The client sends a request message to the server, the server receives it and replies to the client, and the client acknowledges receipt of the server's reply. Once the three handshakes are complete, the client has established a reliable link with the server.

UDP

UDP (User Datagram Protocol), which provides a simple but unreliable messaging service. Much like writing a letter or sending an email in life, there is no need to ask permission or establish a connection with the other party to send the data out, but there is no guarantee that the data sent will reach its destination without error.

Our common ping command is based on the UDP protocol, and the telnet command is based on the TCP protocol.

remember that inVB use inwinsock, Start by dragging two of them onto the formwinsock a control (e.g. button, text box etc) (computing)( Equivalent to instantiating), Then set them toIP、 port、 transfer protocol, It's ready for communication.。 Only inJava in, Communication based on TCP protocol Need to useServerSocket harmonySocket come to finish, UDP protocol-based communication Need to use DatagramSocket harmonyDatagramPacket come to finish。

The following are examples of how network communication is done in Java, in terms of both TCP and UDP.

Communication based on TCP protocol

Server-side code.

import java.io.*;
import java.net.*;
public class Server {	
	public static void main(String[] args) {
		InputStream is=null; 
		OutputStream os=null;
		try{
 			ServerSocket ss=new ServerSocket(5566);          // Create server sockets and bind to port 5566
			Socket s=ss.accept();
			is=s.getInputStream();
			os=s.getOutputStream();
			DataInputStream dis=new DataInputStream(is);
			DataOutputStream dos=new DataOutputStream(os);
			String message=null;
 			if((message=dis.readUTF())!=null){ //Receive and output the message from the client of this connection
				System.out.println("Client:"+message);
			}
			dos.writeUTF("Hello, Client!");                // To the client of this connection Send a message
			dis.close();
			dos.close();
			s.close();
		}catch(ConnectException ex){
			ex.printStackTrace();
		}catch(IOException ex){
			ex.printStackTrace();
		}
	}
}

Client code.

import java.io.*;
import java.net.*;
public class Client {
	public static void main(String[] args) {
		InputStream is=null;
		OutputStream os=null;
		try{
			Socket s=new Socket("127.0.0.1",5566);         // Create a socket and connect it to the127.0.0.1 address( dispenser) of5566 port
			is=s.getInputStream();
			os=s.getOutputStream();
			DataInputStream dis=new DataInputStream(is);
			DataOutputStream dos=new DataOutputStream(os);
			dos.writeUTF("Hello, Server!");               // server-side Send a message
			String message=null;
			if((message=dis.readUTF())!=null){
				System.out.println("Server:"+message);    // Receive and output messages from the server
			}
			dis.close();
			dos.close();
			s.close();			
		}catch(ConnectException ex){
			ex.printStackTrace();
		}catch(IOException ex){
			ex.printStackTrace();
		}
	}
}

Implementation results.

Client.

Servers.

The entire process of connection and interaction is illustrated below.

When executed, the server side is started first, the server side creates a server socket ServerSocket and binds to the specified port, when the execution reaches socket s=ss.accept(), it will "block" (i.e. let the program stay here temporarily), but when the client starts, creates a socket and sends a request to the specified port at the specified address, the ServerSocket accepts the server side's request and returns the client's socket instance to establish a connection with it. The socket was originally meant to be a socket, and it's really quite graphic; the whole process is like plugging the client into the server's socket, and the channel is established. When communication is complete, both parties close the connection.

In the example, the socket's getInputStream() method gets the network connection input and returns a byte input stream object for this socket; the getOutputStream() method returns a byte output stream object for this socket, which is used to write data to the connection object. This reflects the third feature of TCP, "byte stream based", as described above.

UDP protocol-based communication

Server-side code.

import java.net.*;
class UDPServer{
    public static void main(String[] args)throws Exception{
    	// Receive information
        DatagramSocket  server = new DatagramSocket(5050);
        byte[] recvBuf = new byte[1000];
        DatagramPacket recvPacket = new DatagramPacket(recvBuf , recvBuf.length);
        server.receive(recvPacket);
        String recvStr = new String(recvPacket.getData() , 0 , recvPacket.getLength());
        System.out.println("What server has received is:" + recvStr);
        
        // Send a message
        int port = recvPacket.getPort();
        InetAddress addr = recvPacket.getAddress();
        String sendStr = "Hello ! I'm Server";
        byte[] sendBuf = new String("Hello Client! I'm Server!").getBytes();    
        DatagramPacket sendPacket 
            = new DatagramPacket(sendBuf , sendBuf.length , addr , port );
        server.send(sendPacket);
        server.close();
    }
}

Client code.

import java.net.*;
class UDPClient{
    public static void main(String[] args)throws Exception{
    	// Send a message
        DatagramSocket client = new DatagramSocket();       
        byte[] sendBuf=new String("Hello Server! I'm Client").getBytes();       
        InetAddress addr = InetAddress.getByName("127.0.0.1");
        int port = 5050;
        DatagramPacket sendPacket 
            = new DatagramPacket(sendBuf ,sendBuf.length , InetAddress.getByName("127.0.0.1") , port);
        client.send(sendPacket);
        
        // Receive information
        byte[] recvBuf = new byte[100];
        DatagramPacket recvPacket = new DatagramPacket(recvBuf , recvBuf.length);
        client.receive(recvPacket);
        String recvStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
        System.out.println("What client has received is:" + recvStr);
        client.close();
    }
}

The entire process is illustrated below.

After the server starts, it prepares a datagram packet containing the byte array buf for receiving datagrams from the client. After the client starts, it encapsulates the destination address, port, sent content and other information in the DatagramPacket and sends it to the destination (server) through the send() method of the DatagramSocket. The same is true for the process of sending datagrams from the server to the client.

Earlier in the article, we talked about the three TCP handshakes, where the client sends a request, the server accepts the request and returns an acknowledgement, and the client receives the acknowledgement and then sends an acknowledgement to receive the acknowledgement, a simple three-step process that is very complex (and TCP disconnects when Four waves. ). Because the UDP protocol does not require a connection process, it is efficient and fast, but also because of this, UDP is not as reliable as TCP.


Recommended>>
1、The messy Internet of Things
2、ExperienceHow to write a good data analysis report
3、centos7 debugging netcore application dump dump file using lldb
4、Is building on the subway the best way out for Shenzhen which is out of land
5、Why this humancomputer dialogue thing is hard Tsinghua Universityxlab Artificial Intelligence Research Club

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号