Python implements basic Socket server-client communication

      This article uses python to implement basic socket server-client communication, with step-by-step detailed explanations and complete codes, as needed.

(1) Server code:

1. Import the built-in socket module and create a socket instance. The server needs to use bind to bind the instance to the specified domain name and port. The domain name and port number are passed in in a tuple

import socket

#创建 socket对象
socket_server=socket.socket()

# 绑定 socket_server到指定的ip地址
socket_server.bind(("localhost",8888))

2. Set up port monitoring, write numbers in listen() to indicate the number of connections that can be accepted

#监听端口
socket_server.listen(1)

3. Use the accept method to wait for the client to connect. This method is a blocking method. If there is no connection, it will always be blocked at this step. A successful connection will return a tuple, which contains the connection object and client address information respectively 

result=socket_server.accept()
conn=result[0]  #客户端连接对象
address=result[1]  #客户端地址信息

4. Use the recv method of the connection object to receive the message sent by the client. The buffer size of 1024 table can be set by yourself and decoded into UTF-8 format

   data = conn.recv(1024).decode("UTF-8")

   print(f"客户端发来的消息是:{data}")

5. Use the send method of the connection object to send a message to the client

msg=input("请输入回复的消息:")
conn.send(msg.encode("UTF-8"))

6. Disconnect the link after the communication ends

conn.close()
socket_server.close()

Complete server code:

import socket

#创建 socket对象
socket_server=socket.socket()

# 绑定 socket_server到指定的ip地址
socket_server.bind(("localhost",8888))

#监听端口, listen()内书写数字,表示可以接受链接的数量
socket_server.listen(1)

#等待客户端连接,接收到的 result是一个二元元组, accept()是一个阻塞的方法,如果没有连接不会往下执行
result=socket_server.accept()
conn=result[0]  #客户端连接对象
address=result[1]  #客户端地址信息

print(f"接收到的客户端连接信息为{address}")

while True:
   #接收客户端信息,recv接受的参数是缓冲区大小,一般1024即可,返回的是一个字节数组,bytes对象,不是字符串,再将其decode解码为字符串对象
   data = conn.recv(1024).decode("UTF-8")

   print(f"客户端发来的消息是:{data}")

   #回复消息
   msg=input("请输入回复的消息:")

   if msg=='exit':
       break

   conn.send(msg.encode("UTF-8"))

#关闭连接
conn.close()
socket_server.close()

(1) Client code:

1. Introduce the built-in socket module, create a socket instance, and then link the domain name and port of the server, and also pass in tuples as parameters

import socket

#创建 socket对象
socket_client=socket.socket()

# 让 socket对象 socket_client 连接到服务端
socket_client.connect(("localhost",8888))

2. Then you can use send to send a message to the server

msg=input("请输入你要发送的消息:")

socket_client.send(msg.encode("UTF-8"))

3. Use recv to wait for the reply message from the server after sending, and also need to set the buffer and decode

   data=socket_client.recv(1024).decode("UTF-8")
   print(f"服务器回复的消息为:{data}")

4. Disconnect the link after the communication ends

socket_client.close()

Complete client code:

import socket

#创建 socket对象
socket_client=socket.socket()

# 让 socket对象 socket_client 连接到服务端
socket_client.connect(("localhost",8888))

while True:
   msg=input("请输入你要发送的消息:")

   if msg=='exit':
      break

   #发送消息
   socket_client.send(msg.encode("UTF-8"))
   #接收消息
   data=socket_client.recv(1024).decode("UTF-8")
   print(f"服务器回复的消息为:{data}")

socket_client.close()

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/130619144