1.实现一对一的进行沟通交流
(1).服务端代码如下:
import socket
server = socket.socket()
server.bind(("localhost",8000)) #绑定要监听的窗口
server.listen(5) #监听
conn,address = server.accept() #等待接收数据,一个是对方的标记位,一个是对方的地址
while True:
data = conn.recv(1024) #接收数据,谁发数据给我我就用谁的标记位进行接收
#recv 接收
print("recv:",data)
if data == "exit":
print("客户端断开连接....")
break
msg = raw_input("请输入消息:")
conn.send(msg)#发送数据,要发给谁就用谁的标记位
server.close()
(2).客户端代码如下:
import socket
client = socket.socket() #声明socket类型,同时生成socket连接对象
client.connect(("localhost",2159))
while True:
msg =raw_input("请输入消息:")
if len(msg) == 0:
continue
elif msg == "exit":
break
client.send(msg.encode("utf-8"))
data = client.recv(1024)
print(data.decode())
client.close()