python的socket编程流程跟java差不过,服务器端为创建socket对象,bind(),listen(),accept(),read(),write(),客户端主要是创建socket对象,connect(),write(),read()
下面就来写一个客户端每秒给服务器发送一个数字i,服务器把这个数字收到后打印出来并重新发送回客户端,同时客户端也打印出来
#!encoding=utf-8
#服务器端socket
from socket import *
import threading
def get(s):
while True:
data = s.recv(1024)
print "receive:",str(data)
s.send(data)
s = socket(AF_INET,SOCK_STREAM)#创建套接字
s.bind(("",8888))#绑定端口
s.listen(5)#监听
while True:
client,addr = s.accept()#接受连接
print str(addr)
t = threading.Thread(target=get,name="",args=(client,))
t.start()
#!encoding=utf-8
#客户端socket
from socket import *
import threading
from time import sleep
def get(s):
while True:
data = s.recv(1024)
print "receive:",str(data)
s = socket(AF_INET,SOCK_STREAM)
s.connect(("localhost",8888))
t = threading.Thread(target=get,name="",args=(s,))
t.start()
for i in range(0,10):
s.send(str(i).encode("ascii"))
sleep(1)