java achieve TCP communication

1 Overview

TCP communication via the Socket and ServerSocket implementation, use this example with a swing, in fact, sent a communication with a ServerSocker Socket before the author, here , here is the article modifications made in this example.
In fact, the principle is very simple , is a server a client, the server side after created ServerSocket, use the accept () congestion has been waiting for the client to send socket.
well, no nonsense. into the topic.

2. server

swing part not say, talk about the main operations

(1) New ServerSocket

ServerSocket serverSocket = null;
serverSocket = new ServerSocket(12345);//一个不被占用的端口即可

The method of construction of the port parameters, using the default local ip.
The ServerSocket constructor has three,

ServerSocket(int port);
ServerSocket(int port,int backlog);
ServerSocker(int poer,int backlog,InetAddress ip);

Details can be seen here

(2) receiving socket

Socket socket = serverSocket.accept();

The Socket a return (), waits, in the blocked state.
Usually provided a while (true) receiving cycle.

(3) Data processing

Use DataInputStream and DataOutputStream:

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
DataOutputStram outputStream = new DataOutputStream(socket.getOutputStream());

Is then used to read and write methods.
Note that when closed together to close the like after completion of input and output, that is, not so:

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String data = inputStream.readUTF();
inputStream.close();
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("ok");
outputStream.close();

In this case getInputStream () is no problem, but to getOutputStream () when there is a problem, will prompt an exception:
Here Insert Picture Description
. IS the Socket Closed
So the solution is to wait after the output finish before closing with:

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String data = inputStream.readUTF();
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("ok");
inputStream.close();//等输出完成后再关闭
outputStream.close();

(4) the complete code Server.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;

public class Server {
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Server");
        JPanel panel = new JPanel();
        JTextArea text = new JTextArea();

        panel.add(text);
        frame.setContentPane(panel);
        frame.setSize(600, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(12345);
            while (true)
            {
                Socket socket = serverSocket.accept();
                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                text.setText(inputStream.readUTF());

                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                outputStream.writeUTF("ok");
                inputStream.close();
                outputStream.close();
                socket.close();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                serverSocket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

3. Client

Operation is to open a client Socket, and then can obtain the corresponding input and output of the stream through the socket.

(1) Create a new Socket

Socket socket = new Socket("127.0.0.1",12345);//这个端口与服务端的端口对应

Socket three constructors:

Socket(InetAddress ip,int port);
Socket(String ip,int port);
Socket(InetAddress ip,int port,InetAddress localIp,int localPort);
Socket(String ip,int port,InetAddress localIp,int localPort);

Details can be seen here

(2) Input Output

Also use DataInputStream and DataOutputStream:

DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());

(3) complete code Client.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.*;
import java.awt.GridLayout;
public class Client
{
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JTextArea text = new JTextArea();
        JButton send = new JButton();
        GridLayout layout = new GridLayout(2, 1, 0, 5);

        frame.setTitle("Client");
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setSize(600, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(layout);

        frame.add(text);
        frame.add(send);
        send.setText("send");
        send.addActionListener(v ->
        {
            try
            {
                String host = "127.0.0.1";
                int port = 12345;
                Socket socket = new Socket(host, port);
                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                outputStream.writeUTF(text.getText());

                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                text.setText(inputStream.readUTF());
                outputStream.close();
                inputStream.close();
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        });
    }
}

4. Test

First open the server, and then open the client, the server set up here to return to the client's information is "ok".
Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/Blueeeeeeee/p/11986836.html