Ubuntu启一个tcp server,client去连接

1、在~/source/code/python目录下创建两个py文件:

server_8079.py、client_8079.py

server_8079.py的代码:

python 复制代码
# server.py
import socket

def start_server(host, port):
    # 创建一个TCP/IP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # 绑定套接字到地址和端口
    server_socket.bind((host, port))
    
    # 监听传入连接
    server_socket.listen(1)
    print(f"Server listening on {host}:{port}")
    
    while True:
        # 等待连接
        client_socket, addr = server_socket.accept()
        try:
            print(f"Connection from {addr}")
            
            # 接收数据
            data = client_socket.recv(1024)
            print(f"Received: {data.decode('utf-8')}")
            
            # 发送响应
            response = "Hello from server!"
            client_socket.sendall(response.encode('utf-8'))
        finally:
            # 清理连接
            client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8079
    start_server(HOST, PORT)

client_8079.py的代码:

python 复制代码
# client.py
import socket

def start_client(host, port):
    # 创建一个TCP/IP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # 连接到服务器
        client_socket.connect((host, port))
        
        # 发送数据
        message = "Hello from client!"
        client_socket.sendall(message.encode('utf-8'))
        
        # 接收响应
        response = client_socket.recv(1024)
        print(f"Received: {response.decode('utf-8')}")
    finally:
        # 清理连接
        client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8079
    start_client(HOST, PORT)

打开2个terminal:

在第1个terminal输入:

python3 server_8079.py

在第2个terminal输入:

python3 client_8079.py

相关推荐
一只fish17 小时前
Oracle官方文档翻译《Database Concepts 26ai》第7章-数据完整性
数据库·oracle
Gauss松鼠会17 小时前
【GaussDB】GaussDB 常见问题及解决方案汇总
java·数据库·算法·性能优化·gaussdb·经验总结
云边云科技_云网融合17 小时前
云边云全栈 SD-WAN/SASE 运维服务:构建企业数字网络的坚实后盾
数据库·人工智能·云计算
_codemonster17 小时前
测试用例怎么写
运维·服务器·测试用例
eggrall17 小时前
Linux信号——信号产生
linux·运维·服务器
zincsweet17 小时前
虚拟地址空间
linux
Ha_To17 小时前
26.5.19 未授权漏洞
linux·服务器·网络
张道宁17 小时前
从零搭建化工园区 AI 安防监控系统:技术方案、落地实现与工程反思
运维·服务器
bqq1986102617 小时前
Redis持久化
数据结构·数据库·redis·缓存