This is the sixth day of my participation in the More text Challenge. For details, see more text Challenge

This article is participating in the “Java Theme Month – Java Development in action”. See the link to the event for more details


Related articles

Java network programming: Java network programming


First, TCP to send messages

Client code:

/** * Client */
public class TcpClientDemo {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;

        // First, you must know the server address and port number
        // Remember not to throw the exception, catch easy handling
        try {
            // The server address is received with InetAddress
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            / / the port number
            int port = 7777;
            // Create a socket link
            socket = new Socket(inetAddress,port);
            // When sending a message, send it as an IO stream. Send the message as an output stream
            os = socket.getOutputStream();

            // Create a Scanner object that accepts input from the console
            Scanner input=new Scanner(System.in);
            // Accept String
            String messge = input.next();

            // Send the message
            os.write(messge.getBytes(StandardCharsets.UTF_8));



        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // This is the point!! Don't forget to close links and streams
            if(socket ! =null) {try {
                    socket.close();
                } catch(IOException e) { e.printStackTrace(); }}if(os ! =null) {try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Copy the code

Server code:

/** * Server */
public class TcpServerDemo {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        // Set up a server first
        try {
            / / 1, an IP address
            serverSocket = new ServerSocket(7777);

            while (true) {
                //2. Wait for client to connect
                socket = serverSocket.accept();
                //3. We need to read the customer's message. The receiving message must be the input stream
                is = socket.getInputStream();

                // At this point, the message has been received. How do we read it?
                // Pipe the output stream, ByteArrayOutputStream
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];// Byte array to accept
                int length;/ / the length
                while((length = is.read(buffer)) ! = -1) {
                    byteArrayOutputStream.write(buffer, 0, length); } System.out.println(byteArrayOutputStream.toString()); }}catch (Exception e) {
            e.printStackTrace();
        }finally {
            // Similarly, close the stream
            if(serverSocket ! =null) {try {
                    serverSocket.close();
                } catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {try {
                    socket.close();
                } catch(IOException e) { e.printStackTrace(); }}if(is ! =null) {try {
                    is.close();
                } catch(IOException e) { e.printStackTrace(); }}if(byteArrayOutputStream ! =null) {try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Copy the code

Client execution result:

The server accepts the result:

Summary: The code speaks!

  • The client

    • Connecting to server Socket
    • Send a message
  • The service side

    • The port ServerScoket on which the service is established
    • Wait for the user to accept the connection
    • Receive messages from users

2. TCP file upload

  • Client code
/** * Client */
public class TcpUplodeFileClient {
    public static void main(String[] args) throws Exception{
        // create a Socket connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 7777);
        //2, create an output stream
        OutputStream os = socket.getOutputStream();
        //3
        FileInputStream fis = new FileInputStream(new File("C: \ \ Users \ \ butyl greatly greatly useful files \ \ Desktop \ \ \ \ test JPG"));
        //4
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) ! = -1) {
            os.write(buffer, 0, len);
        }

        // Notify the server that I have finished
        socket.shutdownOutput();    // I have finished transmitting!

        // Make sure the server has received the connection before disconnecting
        InputStream inputStream = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while((len2 = inputStream.read(buffer2)) ! = -1) {
            baos.write(buffer2, 0, len2);
        }
        System.out.println(baos.toString());

        //5. Close resourcesbaos.close(); inputStream.close(); fis.close(); os.close(); socket.close(); }}Copy the code
  • Server code
/** * Server */
public class TcpUplodeFileServer {
    public static void main(String[] args) throws Exception{
        // Create a service
        ServerSocket serverSocket = new ServerSocket(7777);
        // Listen for connections
        Socket socket = serverSocket.accept();
        // Get the input stream
        InputStream is = socket.getInputStream();
        // File output
        FileOutputStream fos = new FileOutputStream(new File("test.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len=is.read(buffer)) ! = -1){
            fos.write(buffer,0,len);
        }
        // Notify the client that the reception is complete
        OutputStream os = socket.getOutputStream();
        os.write("Acceptance completed".getBytes());

        // Remember to shut down all resourcesserverSocket.close(); socket.close(); is.close(); os.close(); }}Copy the code
  • Client execution result:

  • Execution result of the server


The road ahead will be long and long, but I will keep searching. If you think I blogger’s writing is good! Writing is not easy, please like, follow, comment to encourage the blogger ~hahah