1234567891011121314151617181920212223242526272829303132333435363738394041 |
- import socket
-
- def start_server(port):
- # 创建一个socket对象
- server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
- # 绑定到指定的IP地址和端口
- # 如果你想监听所有可用的网络接口,可以使用空字符串('')作为IP地址
- server_address = ('', port)
- print(f'Starting up on {server_address[1]}')
- server_socket.bind(server_address)
-
- # 开始监听连接
- server_socket.listen(1)
-
- while True:
- # 等待客户端连接
- print('Waiting for a connection')
- connection, client_address = server_socket.accept()
-
- try:
- print(f'Connection from {client_address}')
-
- # 接收数据,最多1024字节
- while True:
- data = connection.recv(1024)
- print(f'Received {len(data)} bytes from {client_address}')
-
- if not data:
- break
-
- # 向客户端发送数据
- connection.sendall(data)
-
- finally:
- # 清理连接
- connection.close()
-
- if __name__ == '__main__':
- port = 8123 # 你可以更改为你想要的端口号
- start_server(port)
|