Chinaunix首页 | 论坛 | 博客

分类: Python/Ruby

2014-02-23 10:49:38

    在《Python核心编程》中有关于如何编写TCP服务端和客户端的程序,现在看看它们是如何实现的。

server端
#!/usr/bin/python
# -*- coding: utf-8 -*-
from socket import *                                        
from time import ctime
from thread import *                                            #thread和socket是两个新的模块.
#同时接受多个用户的连接
#将用户发送的消息同时分发给多个人
#合适的异常处理.
clientSocket = []
BUFSIZ = 1024

#主要调用了socket.recv和socket.send两个方法。
                    def newClientSocket(sock, addr):
while True:
try:
data = sock.recv(BUFSIZ)
if not data:                                         #注意对函数返回结果的检查(非异常)
    break
for allsock in clientSocket :
    if allsock[0] != sock :
        allsock[0].send('[%s] : %s\n' % (ctime(), data))
except Exception:
           print 'client colsed'
           break;
sock.close()
clientSocket.remove((sock, addr))

if __name__ == '__main__' :
HOST = '192.168.12.90' #服务端的IP地址和端口号直接写死.
PORT = 8888
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)                                #这些都是以实例方法的形式被调用的.
while True:
print 'waiting for connection...'
tcpCliSock, addr = tcpSerSock.accept()
clientSocket.append((tcpCliSock, addr))
start_new_thread(newClientSocket, (tcpCliSock, addr))
print '...connected from:', addr
                                tcpSerSock.close()



client 端:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from socket import *
from time import ctime
import sys
from thread import *

def msg(msg):
        print msg
        exit(-1)


          def portcheck(port):
try:
        PORT = int(sys.argv[2])
        if(PORT < 0):
                msg('not a legal port')
except:
        msg('not a legal port')


def paramcheck():
        if 3 != len(sys.argv):
                msg('not enough param')
portcheck(sys.argv[2])

def recvFunction(sock, argv):
while True:
data = sock.recv(BUFSIZ)
           if not data :
                continue
           print data
#print 'input your words > ',

if __name__ == '__main__':
paramcheck();
HOST = sys.argv[1]
PORT = int(sys.argv[2])
ADDR = (HOST, PORT)
BUFSIZ = 1024

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
start_new_thread(recvFunction, (tcpCliSock,0))
while True:
        data1 = raw_input('')
        if not data1: #user input enter key directly
                break
        tcpCliSock.send(data1)
        print ctime(), " : " , data1
                    tcpCliSock.close()

        从上面来看,socket和threaed两个模块起到的关键的作用,看来要学好Python,就需要熟悉常见的各个模块的操作才行。
阅读(496) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~