简单聊天室示例
服务端
程序代码:
import socket
def start_server():
server_address = ('localhost', 9527)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(server_address)
sock.listen(1)
while True:
print('等待连接...')
connection, client_address = sock.accept()
try:
print(f'客户端 {client_address} 已连接')
while True:
data = connection.recv(16)
if not data:
break
print(f'收到 "{data.decode()}"')
connection.sendall(data) # 简单地回显收到的数据
finally:
connection.close()
if __name__ == '__main__':
start_server()
客户端
程序代码:
import socket
def start_client():
server_address = ('localhost', 9527)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(server_address)
try:
while True:
message = input('>> ')
if message.lower() == 'q':
break
sock.sendall(message.encode())
data = sock.recv(1024)
print(f'收到: "{data.decode()}"')
finally:
print('关闭连接')
sock.close()
if __name__ == '__main__':
start_client()
可以通过修改互相发送的内容进行复杂操作。