JAVA-based socket simple network chat program

How to communicate between network processes

Between local interprocess communication (IPC) There are many ways, but can be summarized by the following 4 categories:

  • Messaging (pipes, FIFO, message queues)
  • Synchronization (mutexes, condition variables, read-write locks, and write record file locks, semaphores)
  • Shared Memory (anonymous and named)
  • Remote Procedure Call (Solaris doors and Sun RPC)

But these are not the subject of this article! We want to discuss how communication between network processes? The primary problem is how to uniquely identify a process or communication out of the question! In a local can be uniquely identified processes by PID, but the network it does not work. In fact, TCP / IP protocol suite has helped us solve this problem, "ip address" of the network layer uniquely identifies hosts on the network, and transport layer "protocol + port" applications that can uniquely identify the host (process). Thus using the triple (ip address, protocol, port) in a network can identify the process, process communication network can use this flag to interact with other processes.

Using TCP / IP protocol application programming interfaces commonly used applications: UNIX BSD socket (Socket) of the TLI and UNIX System V (it has been eliminated), to the network communication between processes. For now, almost all applications are based on the socket, but now is the Internet age, the network process communication is everywhere, which is why "Everything socket".

Introduction to TCP

  1.TCP Introduction

    a> TCP protocols: TCP protocol, Transmission Control Protocol (English: Transmission Control Protocol, abbreviated as: TCP) is connection-oriented, reliable byte stream protocol based communication

    1. The connection-oriented: the first connector, and then the communication, like call model

    2. reliable, with respect to the UDP, TCP is more reliable transmission, TCP sequence by a mechanism (connection-oriented mechanism, the transmission response mechanism) to guarantee the transmission reliability

    3. Based on byte stream, UDP create UDP socket - DGRAM: datagram-based communication system, each transmitted data is an independent entity, comprising ip address of the target host, port numbers, and content data is transmitted

    b> three steps TCP communications

    1 to establish a connection with the server: based connection-oriented.

            2. The transceive data

  

 

 

          3. Close the connection

  2.TCP Features

    a> connection-oriented

    1. The first establish a connection, then the communication

    2.TCP connection is a one-to-one or one-to-many and may UDP, UDP suitable for broadcast program

    a> reliable transmission: by a sequence of mechanisms to protect the data TCP is more reliable than the transmission of UDP

    1. transmission response mechanism

    2. timeout retransmission mechanism

    3. error check

    4. Flow control / congestion management

JavaSocket Programming

        In the Java environment, Socket programming mainly refers to network programming based on TCP / IP protocols.

 

        Socket work process consists of the following four steps:

  (1) Create a Socket;

  (2) Open Socket connection to an input / output streams;

  (3) Socket according to a certain protocol for read / write operation;

  (4) Close Socket

 

The java Socket class includes two: Socket (client) and the ServerSocket (server)

1) Socket class

    Socket class: This class implements client sockets, socket refers to the endpoint of communication between the two devices. Constructors public Socket (String host, int port ): create socket connection object and the specified port number on the specified host. If the specified host is null, the equivalent of the specified address as the loopback address.
    Member method:

         public InputStream getInputStream (): returns the input stream for this socket. If this Scoket having associated channel, all of the generated operation InputStream also associated with the channel. Close-generated InputStream will close the associated Socket.

    public OutputStream getOutputStream (): returns the output stream for this socket. If this Scoket having associated channel, all of the generated operation OutputStream also associated with this channel. Close-generated OutputStream will close the associated Socket.
    public void close (): Closes this socket. Once a socket is closed, it can not be reused. Close this socket will close the associated InputStream and OutputStream.
    public void shutdownOutput (): disable socket output stream. Any previously written data to be transmitted, followed by terminating the output stream.

 

 


  2) Class ServerSocket
  ServerSocket Class: This class implements server socket, the object is waiting for a request over the network.

  Construction method

 

 

     public ServerSocket (int port): With this construction method when creating ServerSocket object, can be bound to a specific port number, the port number is a port parameter.

    Configuration example, as follows: ServerSocket server = new ServerSocket (6666);

  Member method

    public Socket accept (): listens for and accepts the connection, returns a new Socket object, and for clients communicate. This method
will block until the connection is established.

socket in TCP three-way handshake to establish a connection Detailed

We know tcp establish a connection to a "three-way handshake" that exchange three packets. Process substantially as follows:

  • The client sends the server a SYN J
  • Server responds with a SYN K to the client, and the SYN J confirmation ACK J + 1
  • Think of a client server sends acknowledgment ACK K + 1

Only three-way handshake would be finished, but that several functions in this three-way handshake occurs in the socket in it? See below:

image

 

从图中可以看出,当客户端调用connect时,触发了连接请求,向服务器发送了SYN J包,这时connect进入阻塞状态;服务器监听到连接请求,即收到SYN J包,调用accept函数接收请求向客户端发送SYN K ,ACK J+1,这时accept进入阻塞状态;客户端收到服务器的SYN K ,ACK J+1之后,这时connect返回,并对SYN K进行确认;服务器收到ACK K+1时,accept返回,至此三次握手完毕,连接建立。

客户端的connect在三次握手的第二个次返回,而服务器端的accept在三次握手的第三次返回。

 

socket中TCP的四次握手释放连接详解

上面介绍了socket中TCP的三次握手建立过程,及其涉及的socket函数。现在我们介绍socket中的四次握手释放连接的过程,请看下图:

image

 

图示过程如下:

  • 某个应用进程首先调用close主动关闭连接,这时TCP发送一个FIN M;
  • 另一端接收到FIN M之后,执行被动关闭,对这个FIN进行确认。它的接收也作为文件结束符传递给应用进程,因为FIN的接收意味着应用进程在相应的连接上再也接收不到额外数据;
  • 一段时间之后,接收到文件结束符的应用进程调用close关闭它的socket。这导致它的TCP也发送一个FIN N;
  • 接收到这个FIN的源发送端TCP对它进行确认。

这样每个方向上都有一个FIN和ACK。

Java的Socket库函数与Linux的Socket系统调用之间的区别:

Java通过JVM实现了优良的跨平台性,同一段写好的代码,移植到不同的操作系统上可直接执行,不受操作系统的限制,一处编译,到处执行,JAVA的SOCKET编程的底层原理是JVM将JAVA程序解析出来的参数传递给所对应的C++程序,由C++执行完之后回传给JAVA。

而LINUX自带的SOCKET编程只能再LINUX操作系统下使用,同时JAVA与LINUX的API也不一致。

一个小例子:

服务端代码:

package ray;
import java.io.*;
import java.net.*;
public class Server {
    private static ServerSocket server;

    public static void main(String[] args) throws IOException{
        server = new ServerSocket(1100);
        System.out.println("服务器启动成功,等待用户接入...");
        //等待用户接入,直到有用户接入为止,Socket对象表示客户端
        Socket client = server.accept();
        //得到接入客户端的IP地址
        System.out.println("有客户端接入,客户IP:" + client.getInetAddress());
        InputStream in = client.getInputStream();//从客户端生成网络输入流,用于接收来自网络的数据
        
        OutputStream out = client.getOutputStream();//从客户端生成网络输出流,用来把数据发送到网络上

        byte[] bt = new byte[1024];//定义一个字节数组,用来存储网络数据
        int len = in.read(bt);//将网络数据写入字节数组
        String data = new String(bt, 0 , len);//将网络数据转换为字符串数据
        System.out.println("来自客户端的消息:" + data);
        out.write("我是服务器,欢迎光临".getBytes());//服务器端数据发送(以字节数组形式)
        client.close();//关闭套接字
    }
}

客户端代码:

package ray;
import java.io.*;
import java.net.*;
public class Client {
    private static Socket client;

    public static void main(String[] args) throws UnknownHostException, IOException {
        client = new Socket("127.0.0.1", 1100);
        System.out.println("连接服务器成功");
        InputStream in = client.getInputStream();//从客户端生成网络输入流,用于接收网络数据
        OutputStream out = client.getOutputStream();//从客户端生成网络输出流,用来发送数据
        out.write("我是客户端,欢迎光临".getBytes());//客户端数据发送
        byte[] bt = new byte[1024];//定义一个字节数组,用来存储网络数据
        int len = in.read(bt);//将网络数据写入字节数组
        String data = new String(bt, 0 ,len);//将网络数据转换为字符串数据
        System.out.println("来自服务器的消息:" + data);
        client.close();//关闭套接字
    }
}

运行结果展示:

服务器端:

 

 

 

 

 

 

 

  

Guess you like

Origin www.cnblogs.com/zzydexiaowu/p/11988675.html