使用python的标准模块socket来创建服务器和客户端
1.创建TCP服务器
# -*- coding:utf-8 -*-
import socket
import time
HOST = "localhost"
PORT = 8003
ADDR = (HOST, PORT)
so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
so.bind(ADDR) # 因为服务器需要监听一个端口,所以需要绑定一个服务器
so.listen(2) # 监听客户端的连接
while True:
cso, address = so.accept() # 为客户端和服务器创建一个新的socket
while True:
recv_data = cso.recv(1024)
print "server recv data:%s" %(recv_data)
if not recv_data:
cso.close()
recv_data = recv_data + " " + str(time.ctime())
cso.send(recv_data)2. 创建TCP客户端
# -*- coding:utf-8 -*-
import socket
HOST = "localhost"
PORT = 8003
ADDR = (HOST, PORT)
co = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
co.connect(ADDR)
while True:
data = raw_input()
if not data:
co.close()
co.send(data)
recv_data = co.recv(1024)
if not recv_data:
co.close()
print "client recv data:", recv_data