Java Socket Programming

Source: Internet
Author: User

I. Overview of network programming

Network programming refers to writing programs that run on multiple devices (computers) that are connected through the network.

The J2SE API in the java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without focusing on the details of the communication.

The java.net package provides support for two common network protocols:

    • TCP:TCP is the abbreviation for Transmission Control Protocol, which guarantees reliable communication between two applications. Usually used for Internet protocols, which are called TCP/IP.

The TCP protocol is a connection-oriented communication protocol that establishes a logical connection between the sending and receiving ends before transmitting data, and then transmits the data, which provides reliable and error-free data transfer between the two computers. In a TCP connection, it must be clear that the client and server side, the client sends the connection request to the service side, each connection creation will need to go through "three handshake". The first handshake, the client sends a connection request to the server, waits for the server to confirm, the second handshake, the server sends back a response to the client, notifies the client that the connection request was received, the third handshake, and the client again sent a confirmation message to the server confirming the connection.

    • UDP:UDP is an abbreviation for the User Datagram Protocol, a non-connected protocol. A packet that provides the data to be sent between applications.

UDP is a non-connected communication protocol, that is, at the time of data transmission, there is no logical connection between the sending and receiving sides. Simply put, when a computer sends data to another computer, the sender does not confirm that the receiver is present, it sends out the data, and the receiving side does not feed back to the sender when it receives the data.

Because the use of UDP protocol consumes small resources and high communication efficiency, it is usually used for the transmission of audio, video and ordinary data, such as video conferencing using the UDP protocol, because this situation even if the occasional loss of one or two packets, will not have too much impact on the reception results.
Instead, the socket socket uses TCP to provide communication opportunities between the two computers.

Ii. the concept of Socketsocket

The two programs on the network realize the exchange of data through a two-way communication connection, one end of this bidirectional link is called a socket. Sockets are typically used to connect clients and service parties. Sockets are a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number. However, the type of protocol supported by the socket is not only TCP/IP, so there is no necessary connection between the two. In the Java environment, socket programming mainly refers to the network programming based on TCP/IP protocol.

Socket Communication Process

The client program creates a socket and tries to connect to the server's socket.

When the connection is established, the server creates a Socket object. The client and server can now communicate by writing and reading to the Socket object.

The Java.net.Socket class represents a socket, and the Java.net.ServerSocket class provides a mechanism for the server program to listen to the client and establish a connection with them.

The following steps occur when a TCP connection is established between two computers using sockets:

    • The server instantiates a ServerSocket object that communicates through the port on the server.
    • The server calls the Accept () method of the ServerSocket class, and the method waits until the client connects to the given port on the server.
    • When the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
    • The constructor of the Socket class attempts to connect the client to the specified server and port number. If the communication is established, a Socket object is created on the client to communicate with the server.
    • On the server side, the Accept () method returns a new socket reference to the server that is connected to the client's socket.

After the connection is established, each socket has an output stream and an input stream by using the I/O stream, and the client's output is streamed to the server-side input stream, and the client's input is streamed to the server-side output stream.

TCP is a two-way communication protocol, so data can be sent over two data streams at the same time. Here are some classes that provide a complete set of useful ways to implement a socket.

Service side
    1. Creating ServerSocket objects, binding listening ports
    2. Listening for client requests via the Accept () method
    3. After the connection is established, read the request information sent by the client through the input stream
    4. Sending accent information to the client via output flow
    5. Close related Resources

code example:

/*** 基于TCP协议的Socket通信,实现用户登录,服务端*///1、创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口    ServerSocket serverSocket =newServerSocket(10086);//1024-65535的某个端口//2、调用accept()方法开始监听,等待客户端的连接    Socket socket = serverSocket.accept();//3、获取输入流,并读取客户端信息    InputStream is = socket.getInputStream();    InputStreamReader isr =newInputStreamReader(is);    BufferedReader br =newBufferedReader(isr);    String info =null;    while((info=br.readLine())!=null){     System.out.println("我是服务器,客户端说:"+info);    }    socket.shutdownInput();//关闭输入流//4、获取输出流,响应客户端的请求    OutputStream os = socket.getOutputStream();    PrintWriter pw = new PrintWriter(os);    pw.write("欢迎您!");    pw.flush();//5、关闭资源    pw.close();    os.close();    br.close();    isr.close();    is.close();    socket.close();    serverSocket.close();    
Client
    1. Create a socket object that indicates the address and port number of the server you want to connect to
    2. After the connection is established, the request information is sent through the output stream to the server
    3. Get information about the server response via the input stream
    4. Close Response Resource

code example:

//客户端//1、创建客户端Socket,指定服务器地址和端口    Socket socket =newSocket("localhost",10086);//2、获取输出流,向服务器端发送信息    OutputStream os = socket.getOutputStream();//字节输出流    PrintWriter pw =newPrintWriter(os);//将输出流包装成打印流    pw.write("用户名:admin;密码:123");    pw.flush();    socket.shutdownOutput();//3、获取输入流,并读取服务器端的响应信息    InputStream is = socket.getInputStream();    BufferedReader br = new BufferedReader(new     InputStreamReader(is));    String info = null;    while((info=br.readLine())!null){        System.out.println("我是客户端,服务器说:"+info);}//4、关闭资源    br.close();    is.close();    pw.close();    os.close();    socket.close();
Third, the relevant source code analysis (1) ServerSocket class

The server application obtains a port by using the Java.net.ServerSocket class and listens for client requests.

Construction method
public ServerSocket(int port) throws IOException创建绑定到特定端口的服务器套接字。public ServerSocket(int port, int backlog) throws IOException利用指定的 backlog(连接队列的最大长度,队列满时拒绝下一个连接) 创建服务器套接字并将其绑定到指定的本地端口号。public ServerSocket(int port, int backlog, InetAddress address) throws IOException使用指定的端口、侦听 backlog 和要绑定到的本地 IP 地址创建服务器(客户端IP)。public ServerSocket() throws IOException创建非绑定服务器套接字。
Common methods
public int getLocalPort()返回此套接字在其上侦听的端口。public Socket accept() throws IOException侦听并接受到此套接字的连接。public void setSoTimeout(int timeout)通过指定超时值启用/禁用 SO_TIMEOUT,以毫秒为单位。public void bind(SocketAddress host, int backlog)将 ServerSocket 绑定到特定地址(IP 地址和端口号)。
(2) Socket class

The Java.net.Socket class represents a socket that both the client and the server use to communicate with each other. The client wants to get a socket object by instantiating it, and the server obtains a socket object through the Accept () method's return value.

The socket provides two external instantiation methods, namely a connection-oriented socket instance, for a non-connected socket instance. its core is whether to invoke the local connect () method.

Construction method
public Socket(String host, int port) throws UnknownHostException, IOException.创建一个流套接字并将其连接到指定主机上的指定端口号。public Socket(InetAddress host, int port) throws IOException创建一个流套接字并将其连接到指定 IP 地址的指定端口号。public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.创建一个套接字并将其连接到指定远程主机上的指定远程端口。(localAddress:the local address the socket is bound to)public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.创建一个套接字并将其连接到指定远程地址上的指定远程端口。public Socket()通过系统默认类型的 SocketImpl 创建未连接套接字。
Common methods
public void connect(SocketAddress host, int timeout) throws IOException将此套接字连接到服务器,并指定一个超时值。public InetAddress getInetAddress()返回套接字连接的地址。public int getPort()返回此套接字连接到的远程端口。public int getLocalPort()返回此套接字绑定到的本地端口。public SocketAddress getRemoteSocketAddress()返回此套接字连接的端点的地址,如果未连接则返回 null。public InputStream getInputStream() throws IOException返回此套接字的输入流。public OutputStream getOutputStream() throws IOException返回此套接字的输出流。public void close() throws IOException关闭此套接字。
(3) InetAddress class
static InetAddress getByAddress(byte[] addr)在给定原始 IP 地址的情况下,返回 InetAddress 对象。static InetAddress getByAddress(String host, byte[] addr)根据提供的主机名和 IP 地址创建 InetAddress。static InetAddress getByName(String host)在给定主机名的情况下确定主机的 IP 地址。String getHostAddress() 返回 IP 地址字符串(以文本表现形式)。String getHostName() 获取此 IP 地址的主机名。static InetAddress getLocalHost()返回本地主机。String toString()将此 IP 地址转换为 String。

UDP socket programming should be using the Datagramsocket class

Then we will share with you some more detailed information about the socket-related classes.

Java Socket Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.