关于实现两台电脑之间的即时通信
环境:
首先准备两台电脑网络互通。
服务端代码:
# -*- encoding: utf-8 -*-
import socket
if __name__ == '__main__':
IP = "" #服务器端可以写"localhost",可以为空字符串"",可以为本机IP地址
port = 40005 #端口号
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP,port))
s.listen(1)
print('listen at port :',port)
conn,addr = s.accept()
print('connected by',addr)
while True:
data = conn.recv(1024)
data = data.decode()#解码
if not data:
break
print('recieved message:',data)
send = input('return:')
conn.sendall(send.encode())#再编码发送
conn.close()
s.close()
客户端代码:
# -*- encoding: utf-8 -*-
import socket
import sys
if __name__ == '__main__':
IP = '172.20.10.6' #填写服务器端的IP地址
port = 40005 #端口号必须一致
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((IP,port))
except Exception as e:
print('server not find or not open')
sys.exit()
while True:
trigger = input("send:")
s.sendall(trigger.encode())
data = s.recv(1024)
data = data.decode()
print('recieved:',data)
if trigger.lower() == '1':#发送1结束连接
break
s.close()