全部博文(140)
分类: Python/Ruby
2014-02-23 10:49:38
#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *from time import ctimefrom thread import * #thread和socket是两个新的模块.#同时接受多个用户的连接#将用户发送的消息同时分发给多个人#合适的异常处理.clientSocket = []BUFSIZ = 1024
#主要调用了socket.recv和socket.send两个方法。
while True:try:
data = sock.recv(BUFSIZ)if not data: #注意对函数返回结果的检查(非异常)breakfor 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 = 8888ADDR = (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()
#!/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)
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 :continueprint data#print 'input your words > ',
if __name__ == '__main__':
paramcheck();
HOST = sys.argv[1]PORT = int(sys.argv[2])ADDR = (HOST, PORT)BUFSIZ = 1024
tcpCliSock.close()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 directlybreaktcpCliSock.send(data1)print ctime(), " : " , data1