Socket related brief introduction 2

write picture description here

Socket communication

The TCP protocol is connection-oriented, reliable, and ordered. It sends data in the form of byte streams, and implements network communication based on the TCP protocol.

Client's Socket
class Server's ServerSocket class

The process is as follows:

write picture description here

Implementation steps of programming communication based on TCP-Socket

1. Create ServerSocket and Socket
2. Open the input stream and output stream connected to the Socket
3. Read and write operations on the Socket according to the protocol
4. Close the input stream and output stream, and close the Socket

Service-Terminal

1. Create a ServerSocket object and establish a listening port.
2. Monitor client requests through the accept() method.
3. After the connection is established, read the information sent by the client through the input stream.
4. Send response information to the client through the output stream.



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

/*
 * 基于TCP协议的Socket通信,实现用户登陆
 * 服务器端
 */
public class Server {
    public static void main(String[] args) {
        try {
            //1.创建一个服务器端Socket,即ServerSocket,指定绑定的端口,并监听此端口
            ServerSocket serverSocket=new ServerSocket(8888);
            Socket socket=null;
            //记录客户端的数量
            int count=0;
            System.out.println("***服务器即将启动,等待客户端的连接***");
            //循环监听等待客户端的连接
            while(true){
                //调用accept()方法开始监听,等待客户端的连接
                socket=serverSocket.accept();
                //创建一个新的线程
                ServerThread serverThread=new ServerThread(socket);
                //启动线程
                serverThread.start();
                //设置线程的优先级,范围设置[1-10],默认位5
                serverThread.setRiority(4);
                count++;//统计客户端的数量
                System.out.println("客户端的数量:"+count);
                InetAddress address=socket.getInetAddress();
                System.out.println("当前客户端的IP:"+address.getHostAddress());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

multithreaded server

Application of multi-threading to realize the communication between the server and multiple
clients , create a Socket and establish a dedicated line connection with the client 4. The two sockets that establish the connection talk on a separate thread 5. The server continues to wait for a new connection



/*
 * 服务器线程处理类
 */
public class ServerThread extends Thread {
    // 和本线程相关的Socket
    Socket socket = null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    //线程执行的操作,响应客户端的请求
    public void run(){
        InputStream is=null;
        InputStreamReader isr=null;
        BufferedReader br=null;
        OutputStream os=null;
        PrintWriter pw=null;
        try {
            //获取输入流,并读取客户端信息
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String info=null;
            while((info=br.readLine())!=null){//循环读取客户端的信息
                System.out.println("我是服务器,客户端说:"+info);
            }
            socket.shutdownInput();//关闭输入流
            //获取输出流,响应客户端的请求
            os = socket.getOutputStream();
            pw = new PrintWriter(os);
            pw.write("欢迎您!");
            pw.flush();//调用flush()方法将缓冲输出
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            //关闭资源
            try {
                if(pw!=null)
                    pw.close();
                if(os!=null)
                    os.close();
                if(br!=null)
                    br.close();
                if(isr!=null)
                    isr.close();
                if(is!=null)
                    is.close();
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

client

1. Create a Socket object and specify the address and port number of the server to be connected to.
2. After the connection is established, the request information is sent to the server through the output stream.
3. Obtain the corresponding information of the server through the input stream
4. Close the related resources

/*
 * 客户端
 */
public class Client {
    public static void main(String[] args) {
        try {
            //1.创建客户端Socket,指定服务器地址和端口
            Socket socket=new Socket("localhost", 8888);
            //2.获取输出流,向服务器端发送信息
            OutputStream os=socket.getOutputStream();//字节输出流
            PrintWriter pw=new PrintWriter(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();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Implementation steps of programming communication based on UDP-Socket

The UDP protocol (User Datagram Protocol) is connectionless, unreliable, and unordered.
When performing data transmission, firstly, the data to be transmitted needs to be defined as a datagram (Datagram), and the Socket (host address and port number) to be reached by the data is indicated in the datagram, and then the datagram is sent out.

Related operation class

DatagramPacket: Represents a datagram packet
DatagramSocket: A class for end-to-end communication

UDP server implementation steps

1. Create a DatagramSocket and specify the port number.
2. Create a DatagramPacket
3. Receive data information sent by the client
4. Read data


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/*
 * 服务器端,实现基于UDP的用户登陆
 */
public class UDPServer {
    public static void main(String[] args) throws IOException {
        /*
         * 接收客户端发送的数据
         */
        //1.创建服务器端DatagramSocket,指定端口
        DatagramSocket socket=new DatagramSocket(8800);
        //2.创建数据报,用于接收客户端发送的数据
        byte[] data =new byte[1024];//创建字节数组,指定接收的数据包的大小
        DatagramPacket packet=new DatagramPacket(data, data.length);
        //3.接收客户端发送的数据
        System.out.println("****服务器端已经启动,等待客户端发送数据");
        socket.receive(packet);//此方法在接收到数据报之前会一直阻塞
        //4.读取数据
        String info=new String(data, 0, packet.getLength());
        System.out.println("我是服务器,客户端说:"+info);

        /*
         * 向客户端响应数据
         */
        //1.定义客户端的地址、端口号、数据
        InetAddress address=packet.getAddress();
        int port=packet.getPort();
        byte[] data2="欢迎您!".getBytes();
        //2.创建数据报,包含响应的数据信息
        DatagramPacket packet2=new DatagramPacket(data2, data2.length, address, port);
        //3.响应客户端
        socket.send(packet2);
        //4.关闭资源
        socket.close();
    }
}

UDP client implementation steps

1. Define the sending information
2. Create a DatagramPacket, which contains the information to be sent
3. Create a DatagramSocket
4. Send data


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/*
 * 客户端
 */
public class UDPClient {
    public static void main(String[] args) throws IOException {
        /*
         * 向服务器端发送数据
         */
        //1.定义服务器的地址、端口号、数据
        InetAddress address=InetAddress.getByName("localhost");
        int port=8800;
        byte[] data="用户名:admin;密码:123".getBytes();
        //2.创建数据报,包含发送的数据信息
        DatagramPacket packet=new DatagramPacket(data, data.length, address, port);
        //3.创建DatagramSocket对象
        DatagramSocket socket=new DatagramSocket();
        //4.向服务器端发送数据报
        socket.send(packet);

        /*
         * 接收服务器端响应的数据
         */
        //1.创建数据报,用于接收服务器端响应的数据
        byte[] data2=new byte[1024];
        DatagramPacket packet2=new DatagramPacket(data2, data2.length);
        //2.接收服务器响应的数据
        socket.receive(packet2);
        //3.读取数据
        String reply=new String(data2, 0, packet2.getLength());
        System.out.println("我是客户端,服务器说:"+reply);
        //4.关闭资源
        socket.close();
    }
}

Final tip

Multithreading priority

//设置线程的优先级,范围设置[1-10],默认位5
            serverThread.setRiority(4);

Whether to close the output stream and input stream

For the same socket, if the output stream is closed, the socket associated with the output stream will also be closed, so generally it is not necessary to close the stream, just close the socket directly.

Transfer objects using TCP communication

ObjectOutStream oos = new ObjectOutStream();
User u  =new User("admin","123");
oos.writeObejct(u)

Socket programming to transfer files

1. Entity

public class User implements Serializable {
    private String userName;
    private String userId;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public User() {
    }

    ;

    public User(String userName, String userId) {
        this.userName = userName;
        this.userId = userId;
    }

    ;
}

2. Client

OutputStream os=socket.getOutputStream();//字节输出流 
 PrintWriter pwPrintWriter = new PrintWriter(os);//将输出流包装成打印流 
ObjectOutputStream oos = new ObjectOutputStream(os); 
pwPrintWriter.write("用户名:Tom;密码:123"); //传入字符串 
User user = new User("Tom", "123");//传入对象 
oos.writeObject(user); 
pwPrintWriter.flush(); socket.shutdownOutput();
ObjectInputStream din =new ObjectInputStream(inputStream); 
//接收文件写出文件
FileOutputStream fos = new FileOutputStream("File/UDOClient1.txt");
byte[] buf=new byte[1024];
int len;
while ((len = din.read(buf,0,buf.length)) != -1) { fos.write(buf, 0, len); fos.flush(); } fos.close(); 
socket.shutdownInput();

3. Server

ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
User user = (User) is.readObject();
System.out.println("我是服务器,客户端说" + user.getUserName() + ":" + user.getUserId());
socket.shutdownInput();// 关闭输入流
outputStream = socket.getOutputStream();

file = new File("File/Client.txt"); 
fin = new FileInputStream(file);
byte[] sendByte = new byte[1024]; 
ObjectOutputStream obj=new ObjectOutputStream(outputStream);
int length;
while ((length = fin.read(sendByte, 0, sendByte.length))!=-1) { obj.write(sendByte, 0, length);
obj.flush(); }

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325566256&siteId=291194637