client段代码如下:
import sys
from socket import *
serverHost = 'localhost'
serverPort = 1002
message = [b'Hello network world']
if len(sys.argv)> 1:
serverHost =sys.argv[1]
if len(sys.argv) >2:
message = (x.encode() for x in sys.argv[2:])
sockobj = socket(AF_INET , SOCK_STREAM)
sockobj.connect((serverHost , serverPort))
for line in message:
sockobj.send(line)
data = sockobj.recv(1024)
print "client received:" , data
sockobj.close()
from socket import *
myHost = ''
myPort = 1002
sockobj = socket(AF_INET , SOCK_STREAM)
sockobj.bind((myHost , myPort))
sockobj.listen(5)
while True:
connection , address = sockobj.accept()
print "Server connected by" , address
while True:
data = connection.recv(1024)
print "*"*30
print data
if not data:break
connection.send(b'Echo=>'+data)
connection.close()
这段代码就这么简单,就完成了两个计算机基于TCP/IP的通讯。
参考资料:
http://www.cnblogs.com/vamei/archive/2012/10/30/2744955.html