当前位置:编程学习 > python >>

初学python:网络通信

   简单C/S模型,实现两主机通过socke通信。
    服务器端:
ser.py
[python]  
from socket import *  
import thread  
  
PORT=5648  
BUFSIZE=1024  
  
def th():  
    while True:  
        data=raw_input("")  
        if not data:  
            break  
        tcpCliSock.send(data)  
ADDR=("",PORT)  
tcpSerSock=socket(AF_INET,SOCK_STREAM)  
tcpSerSock.bind(ADDR)  
tcpSerSock.listen(5)  
print "waiting fot connection..."  
tcpCliSock,addr=tcpSerSock.accept()  
print "connection from :%s" % str(addr)  
thread.start_new_thread(th,())  
while True:  
    data=tcpCliSock.recv(BUFSIZE)  
    if not data:  
        break  
    print data  
tcpSerSock.close()  
 
    客户端:
cli.py
[python]  
from socket import *  
import thread  
  
HOST='localhost'  
PORT=5648  
BUFSIZE=1024  
ADDR=(HOST,PORT)  
def th(sock):  
    while True:  
        data=raw_input("")  
        if not data:  
            break  
        sock.send(data)  
  
tcpCliSock=socket(AF_INET,SOCK_STREAM)  
tcpCliSock.connect(ADDR)  
  
thread.start_new_thread(th,(tcpCliSock,))  
while True:  
    data=tcpCliSock.recv(BUFSIZE)  
    print data  
tcpCliSock.close()  
 
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,