Python网络编程-socket


Python




0x01.socket网络通信

socket是嵌套字的意思,可以理解为server与client们间的在线会话。


socket与通信协议


关于socket通信可以看这里:

http://queengina.com/2014/10/09/简单理解Socket/




0x02.多线程socket


python下开启一个socket

对于server服务端,python socket需要做4件事情

1.开启socket

2.设置配置socket

3.绑定端口

4.帧监听,收发包


多线程socket

=> server.py

#!/usr/bin/python
# -*- coding:utf-8 -*-
import socket 
import threading 
import time
import sys

clients = [] 
class RecvMsg(threading.Thread): 
    def __init__(self, sock): 
        threading.Thread.__init__(self) 
        self.sock = sock 
    def run(self): 
        global clients 
        while True: 
            msg = self.sock.recv(512) 
            print 'recv=>',msg 
            for client in clients: 
                if client != self.sock:
                        message = {}
                    message['id'] = self.sock
                    message['time'] = time.time()
                    message['type'] = 'server send'
                    print 'send=>', message
                    client.send( str(message) )
                    pass
                pass

def main( port ): 
    sock = socket.socket() 
    sock.bind(( socket.gethostname(), int(port) )) 
    sock.listen(5) 
    while True: 
        client, address = sock.accept() 
        print 'a client connected' 
        if client not in clients: 
            clients.append(client) 
            recvMsg = RecvMsg(client)
            recvMsg.start() 
    sock.close() 

if __name__ == "__main__": 
    port = sys.argv[1]
    main( port ) 

python server.py 56565




=> client.py

#!/usr/bin/python
# -*- coding:utf-8 -*-
import socket  
import threading 
import os,time 
import sys

class RecvMsg(threading.Thread): 
    def __init__(self, sock): 
        threading.Thread.__init__(self) 
        self.sock = sock 

    def run(self): 
        while True: 
            recvMsg = self.sock.recv(512) 
            print 'recv=>',recvMsg 

def sendMsg(sock): 
    msg = time.time()
    message = {} 
    message['id'] = os.getpid() 
    message['msg'] = msg 
    print 'send=>', message 
    sock.send(str(message)) 

def main( port ): 
    sock = socket.socket() 
    sock.connect(( socket.gethostname(), int(port) )) 
    recvMsg = RecvMsg(sock) 
    recvMsg.start() 
        while True:
        time.sleep(1.5) 
        sendMsg(sock) 

if __name__ == "__main__":
    port = sys.argv[1] 
    main( port ) 

python client.py 56565


关于报错

socket模块提供4个error函数。

1.关于一般I/O和通信有关的问题 socket.error

2.与查询地址有关 socket.gaierror

3.与其他地址错误有关 socket.herror

4.与上个socket调用timeout有关 socket.timeout

举个例子:(保存为error.py)

#!/usr/bin/python
# -*- coding:utf-8 -*-
from socket import *
import time,sys

HOST = socket.gethostname()
PORT = sys.argv[0] 
BUFSIZ = 1024
ADDR = ( HOST, int(PORT) )

SerSock = socket(AF_INET, SOCK_STREAM)

try:
    SerSock.bind(ADDR)
except socket.error, e:
    print 'socket.error=>',e
except socket.gaierror, e:
    print 'socket.gaierror=>',e
except socket.herror, e:
    print 'socket.herror=>',e

SerSock.listen(5)

while True:
    print 'waiting for message...'
    CliSock, addr = tcpSerSock.accept()
    print '...connect from :', addr
    while True:
        data = CliSock.recv(BUFSIZ)
        if not data:
            break
        CliSock.send('[%s] %s' % (time.ctime(), data))
    CliSock.close()
SerSock.close()

python error.py 54545







本文出自 夏日小草,转载请注明出处: http://homeway.me/2014/10/21/python-socket-1/


-by小草

2014-10-21 22:34:54

Fork me on GitHub