Python最简单的Python套接字客户端-服务器示例

示例

服务器端:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # 成为服务器套接字,最多5个连接

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print(buf)
    break

客户端:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')

首先运行SocketServer.py,并确保服务器已准备好监听/接收消息,然后客户端将信息发送到服务器;服务器收到某事后,它终止