当前位置:网站首页>ServerSocket and socket connection

ServerSocket and socket connection

2022-06-25 00:21:00 BY-91

summary :

ServerSocket class TCP agreement , Server side , adopt serveSocket.accept(); Method to get socket example
Socket class TCP agreement adopt new Socket() Get instance , establish Socket Object, you need to declare a IP Address and ServerSocket Port number of the object , Only in this way can a connection request be sent to the server

serverSocket.accept()  Accept connection requests from clients , And return a socket . If you are not connected to the client , Thread is blocked , The program can't go on 
 A server can accept connection requests from multiple clients , But only for the first connected socket , Only communicate with the first client , No communication with other clients  
 If you want to serve multiple clients , Client requests that the server receives (Socket socket=serverSocket.accept()) In a cycle , In fact, it's equivalent to having N Servers , Of course, it can be with n Client communications 

1.getInputStream Method can get an input stream , Client's Socket On the object getInputStream Method is actually the data sent back from the server .

2.getOutputStream Method gets an output stream , Client's Socket On the object getOutputStream The output stream obtained by the method is actually the data sent to the server .

 Usage on server side 

1.getInputStream Method gets an input stream , Server side Socket On the object getInputStream The input stream obtained by the method is actually the data stream sent from the client to the server .

2.getOutputStream Method gets an output stream , Server side Socket On the object getOutputStream The output stream obtained by the method is actually the data sent to the client .

Socket Communicate with the browser

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTest {
    //ServerSocket Do the service side 
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            byte[] bytes =  new byte[1024*5];
            int len = inputStream.read(bytes);// Read data from client 
            System.out.println(new String(bytes,0,len));
            // Read the file 
//            FileInputStream fileInputStream = new FileInputStream("D:\\img\\binder.jpg");
            outputStream.write(" From the server ".getBytes());
//            while ((len=fileInputStream.read(bytes))!=-1){
//                outputStream.write(bytes,0,len);
//            }
            outputStream.write(bytes,0,len);
            outputStream.flush();// Send data to client 

//            fileInputStream.close();
            inputStream.close();
            outputStream.close();
//            socket.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

 Insert picture description here

Connection and communication

Server side ServerSocket:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            byte[] bytes =  new byte[1024];
            int len = inputStream.read(bytes);// Read data from client 
            System.out.println(new String(bytes,0,len));
            outputStream.write(" I am the server ".getBytes());
            outputStream.flush();

            outputStream.close();
            inputStream.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }

    }
}

client Socket

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ClientTest {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("192.168.1.43",8080);
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(" Message from client ".getBytes());
            outputStream.flush();
            // Read server messages 
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            System.out.println(new String(bytes,0,len));

            outputStream.close();
            inputStream.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

 Insert picture description here
 Insert picture description here

Socket Keep connected communication

client

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

public class Client {
    public static final int port = 8080;
    public static final String host = "localhost";
    public static void main(String[] args) {
        System.out.println("Client Start...");
        while (true){
            Socket socket = null;
            try{
                // Creates a stream socket and connects it to the specified port number on the specified host 
                socket = new Socket(host,port);

                // Read server-side data 
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                // Send data to the server 
                PrintStream printStream = new PrintStream(outputStream);
                System.out.println(" Send to server :\t");
                String str =  new BufferedReader(new InputStreamReader(System.in)).readLine();
                printStream.println(str);

                String ret = bufferedReader.readLine();
                System.out.println(" Server return :"+ret);
                //  If received  "OK"  Then disconnect 
                if ("OK".equals(ret)) {
                    System.out.println(" The client will close the connection ");
                    Thread.sleep(500);
                    break;
                }
                outputStream.close();
                inputStream.close();
            }catch (Exception e){
                System.out.println(" Client exception "+e.toString());
            }finally {
                if(null != socket){
                    try {
                        socket.close();
                    } catch (IOException exception) {
                        socket = null;
                        System.out.println(" client  finally  abnormal :"+exception.toString());
                        exception.printStackTrace();
                    }
                }
            }
        }

    }
}

Server side

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static final int port = 8080;

    public static void main(String[] args) {
        System.out.println("Server...\n");
        Server server = new Server();
        server.init();
    }

    private void init() {
        try {
            // Create a ServerSocket, Here you can specify the queue length of the connection request 
            //new ServerSocket(port,100); Means when there is... In the queue 100 The first connection request is , If Client Re request connection , Will be Server Refuse 
            ServerSocket serverSocket = new ServerSocket(port,100);
            while (true){
                // Take a connection from the request queue 
                Socket socketClient = serverSocket.accept();
                // Deal with connection 
                new HandlerThread(socketClient);
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
    private class HandlerThread implements Runnable{
        private Socket socket;

        public HandlerThread(Socket client) {
            this.socket = client;
            new Thread(this::run).start();
        }

        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                //  Read client data , The reading and sending methods should be the same as those of the server , Otherwise, it will be thrown  EOFException
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String clientMsg = bufferedReader.readLine();
                //  Processing client data 
                System.out.println(" The client sends a message :" + clientMsg);
                //  Reply to the client 
                PrintStream printStream = new PrintStream(outputStream);
                System.out.print(" Please enter :\t");
                String serverMsg = new BufferedReader(new InputStreamReader(System.in)).readLine();
                printStream.println(serverMsg);

                inputStream.close();
                outputStream.close();
            } catch (IOException exception) {
                System.out.println(" Server exception : " + exception.getMessage());
                exception.printStackTrace();
            }finally {
                if (null != socket){
                    try {
                        socket.close();
                    } catch (IOException exception) {
                        socket =null;
                        System.out.println(" Server side  finally  abnormal :"+exception.toString());
                        exception.printStackTrace();
                    }
                }
            }

        }
    }
}

 Insert picture description here
 Insert picture description here

原网站

版权声明
本文为[BY-91]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210550382375.html