server 与 client 相互通信简例(先运行服务器端,在运行客户端):
server:
'''
Created on 2012-5-10@author : YJ
'''
import socket
s=socket.gethostbyname(socket.gethostname())
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind((s,804))
serversocket.listen(5);
clientsocket,clientaddress=serversocket.accept()
print("Connection from",clientaddress)
while True:
data=clientsocket.recv(1024)
print(data)
newdata = input(">>")
if not newdata:break
output=newdata.encode(encoding='utf_8')
clientsocket.send(output)
serversocket.close()
client:
'''
Created on 2012-5-10@author : YJ
'''
import socket
s=socket.gethostbyname(socket.gethostname())
clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
clientsocket.connect((s,8000))
while True:
data=input(">")
data = data.encode(encoding='utf_8')
clientsocket.send(b''+data)
if not data:break
newdata=clientsocket.recv(1024)
print(newdata)
clientsocket.close()
若要实现两台电脑的交互,将一方的 s 改为对方的IP即可。(IP可以通过cmd中输入ipconfig查看IPv4)