tcp客户端
import socket
def main():
# 创建套接字
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
# tcp_socket.connect("192.168.33.11",7809)
server_ip = input("请输入要连接的服务器")
server_port = int(input("请输入要链接的服务器的端口"))
server_addr = (server_ip, server_port)
tcp_socket.connect(server_addr)
# 发送数据/接收数据
send_data = input("请输入要发送的数据")
tcp_socket.send(send_data.encode("utf-8"))
# 关闭套接字
tcp_socket.close()
if __name__ == "__main__":
main()
E:\python_project\NetWork\venv\Scripts\python.exe E:/python_project/NetWork/TcpClient.py
请输入要连接的服务器192.168.29.2
请输入要链接的服务器的端口8080
请输入要发送的数据ewrefeqw
Process finished with exit code 0
tcp客户端.png
TCP服务端
import socket
def main():
# 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定本地信息
tcp_server_socket.bind(("", 8080))
# 让套接字由主动变为被动
tcp_server_socket.listen(128)
# 等待客户端的连接
new_client_socket, client_addres = tcp_server_socket.accept()
print(new_client_socket, client_addres)
# 接收客户端发送过来的请求
recv_data = new_client_socket.recv(1024)
print(recv_data.decode("gbk"))
# 回送数据给客户端
new_client_socket.send("我接收到了".encode("utf-8"))
# 关闭套接字
new_client_socket.close()
tcp_server_socket.close()
if __name__ == "__main__":
main()
E:\python_project\NetWork\venv\Scripts\python.exe E:/python_project/NetWork/TcpServer.py
<socket.socket fd=496, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.29.2', 8080), raddr=('192.168.29.2', 56825)> ('192.168.29.2', 56825)
你好
Process finished with exit code 0
tcp服务端.png
循环为多个客户端服务
import socket
def main():
# 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定本地信息
tcp_server_socket.bind(("", 8080))
# 让套接字由主动变为被动
tcp_server_socket.listen(128)
# 这个while循环为多个客户端服务
while True:
# 等待客户端的连接
new_client_socket, client_addres = tcp_server_socket.accept()
print(new_client_socket, client_addres)
# 这个while为一个客户端多次使用服务
while True:
# 接收客户端发送过来的请求
recv_data = new_client_socket.recv(1024)
# 客户端发送关闭,我们要解阻塞,断开当前客户端的连接,给其他客户端建立连接的机会
if recv_data:
print(recv_data.decode("gbk"))
# 回送数据给客户端
new_client_socket.send("我接收到了".encode("utf-8"))
else:
print("客户端断开了连接")
break
# 关闭套接字
new_client_socket.close()
tcp_server_socket.close()
if __name__ == "__main__":
main()
E:\python_project\NetWork\venv\Scripts\python.exe E:/python_project/NetWork/TcpServer.py
<socket.socket fd=424, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.29.2', 8080), raddr=('192.168.29.2', 61175)> ('192.168.29.2', 61175)
dada
dada
dada
客户端断开了连接
<socket.socket fd=472, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.29.2', 8080), raddr=('192.168.29.2', 61178)> ('192.168.29.2', 61178)
关闭
关闭
关闭
客户端断开了连接
<socket.socket fd=472, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.29.2', 8080), raddr=('192.168.29.2', 61179)> ('192.168.29.2', 61179)
dada
dada
dada
客户端断开了连接
多个客户端服务.png
网友评论