代码如下:
服务器代码:
import socket
#定义连接信息
HOST = ''
PORT = 8080
ADDRESS = (HOST,PORT)
#定义一个读写的数据的缓存数据大小
BUFFER = 1024
#创建一个tcp套接字对象
tcp_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定主机端口号
tcp_server.bind(ADDRESS)
#监听端口,参数—排队的客户端
tcp_server.listen(1)
while True:
print("准备建立连接......")
server_socket,addr = tcp_server.accept()
print("client already connect! welcome to server: ", addr)
while True:
info = input("请输入您要发送的信息:")
server_socket.send(info.encode("gbk"))
#接收客户端发送的信息
msg = server_socket.recv(BUFFER)
print("client:",msg.decode('utf-8'))
if msg == b'BYE':
#关闭套接字,释放资源
server_socket.close()
break
tcp_server.close()
客户端代码:
import socket
#建立连接信息
TARGET_HOST = '192.168.13.21'
TARGET_PORT = 8080
TARGET_ADDRESS = (TARGET_HOST,TARGET_PORT)
BUFFER = 1024
#创建一个客户端的套接字对象
tcp_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#连接指定的主机
tcp_client.connect(TARGET_ADDRESS)
#收发消息
while True:
msg = tcp_client.recv(BUFFER)
print("server:",msg.decode("gbk"))
#发送消息
info = input("请输入您要发送的信息:")
tcp_client.send(info.encode("UTF-8"))
print("对方已收到您的信息")
if info == "BYE":
tcp_client.close()
break
print("客户端退出!")
网友评论