1. 环境准备
(1) vmware workstation上启动两台虚拟机 rhel5.0 server i386, 每台都有网卡,且配置为NAT方式(因为在学校做实验,用学校的DHCP设备分配IP需要学号/密码验证,而我只有一个学号密码,用Bridge方式只能分配一个IP;故只能采用NAT方式,因为这种方式的DHCP服务器上宿主物理机上虚拟出来的)
(2) 设置网卡配置文件以DHCP方式获取到IP地址
cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0 ONBOOT=yes BOOTPROTO=dhcp
(3) 重启网络服务
service network restart
(4) 注意需要把服务器端的防火墙关闭
service iptables stop
2. TCP socket服务器
select服务器
# -*- coding: gb18030 -*-
import socket, select
host = socket.gethostname()
port = 1234
s = socket.socket()
s.bind((host, port))
s.listen(5)
inputs = [s]
while True:
rs, ws, es = select.select(inputs, [], [])
for r in rs:
if r is s: #r是"服务器端的监听套接字"
c, addr = s.accept()
print 'Got connection from ', addr
inputs.append(c)
else: #r是"服务器端的套接字"
try:
data = r.recv(1024)
disconnected = not data
except socket.error:
disconnected = True
if disconnected:
print r.getpeername(), 'disconnected'
inputs.remove(r)
else:
print data
asyncore服务器(用async_chat处理连接会话)
# -*- coding: gb18030 -*-
from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore
#select在linux和widows上都可以用
#poll在windows上不能用,而且asyncore.loop()中好像用到了poll
PORT = 5005
NAME = "TestChat"
class ChatSession(async_chat):
'''处理服务器和一个用户之间连接的类'''
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server #在session中关联server
self.set_terminator("\r\n")
self.data = []
self.push("Welcome to %s"%self.server.name)
def collect_incoming_data(self, data):
self.data.append(data)
def found_terminator(self):
'''如果发现了一个终止对象,也就发现了一个完整的行,将其广播给所有人'''
line = ''.join(self.data)
self.data = []
self.server.broadcast(line)
def handle_close(self):
async_chat.handle_close(self)
self.server.disconnect(self)
class ChatServer(dispatcher):
'''接受连接并且产生单个会话的类。它会处理其他会话的广播'''
def __init__(self, port, name):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('',port))
self.listen(5)
self.name = name
self.sessions = [] #在server中关联session
def broadcast(self, line):
for session in self.sessions:
session.push(line + "\r\n")
def handle_accept(self):
conn, addr = self.accept()
self.sessions.append(ChatSession(self, conn))
if __name__ == "__main__":
s = ChatServer(PORT, NAME)
try:
asyncore.loop()
except KeyboardInterrupt:
print
3. TCP socket客户机
import socket
import time
host = socket.gethostname()
port = 1234
s = socket.socket()
s.connect((host, port))
while True:
str_to_server = raw_input("send sth. to server: ")
s.send(str_to_server)
#print s.recv(1024)
参考文档
socket — Low-level networking interface: http://docs.python.org/2/library/socket.html
socket programing HOWTO: http://docs.python.org/2/howto/sockets.html
python网络编程 http://www.cnblogs.com/hnrainll/archive/2012/10/25/2738094.html