最簡單的 Python 套接字客戶端 - 伺服器示例

伺服器端:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

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,並確保伺服器已準備好偵聽/接收……然後客戶端將資訊傳送到伺服器; 伺服器收到後,它終止