python 网络编程第一版

--version 1.0 只完成server/client 之间的通信。

1、server端的代码:

#!/usr/bin/python
#!coding:utf-8

from socket import *
import os,sys


if __name__=="__main__":
    #定义套接字
    hostIp='127.0.0.1'
    port=2048
    sock=socket(AF_INET,SOCK_STREAM)
    sock.bind((hostIp,port))
    sock.listen(5)
    print '[info]    开始监听{0}:{1}'.format(hostIp,port)
    while True:
        #接受一个客户端的连接
        conn,addr = sock.accept()
        print '[info]    has recived a client from {0}'.format(addr)
        #与客户端进行交互,直到客户端退出
        while True:
            #接收客户端发来的信息,一次最多收1024字节
            recivedData=conn.recv(1024)
            #由于客户端在断开时会发送一个空串,所以我们用这个上来测试连接是否断开
            if not recivedData : print '[wan]    客户端已经断开连接...'; break;
            print '[info]    this is a infomation from client --> {0}'.format(recivedData.decode())
            #发送信息到客户端
            conn.send('this inforamtion from server --> {0}'.format(recivedData.decode()).encode())
        conn.close()

2、client端的代码:

#!/usr/bin/python
#!coding:utf-8

from socket import *
import os,sys

if __name__ == "__main__":
    #定义套接字
    hostIp='127.0.0.1'
    port=2048
    sock=socket(AF_INET,SOCK_STREAM)
    messages=['hello I am a client']
    messages=messages+sys.argv[1:]
    sock.connect((hostIp,port))
    print '[info]    已经连接到server '
    
    for message in messages:
        sock.send(message.encode())
        print sock.recv(1024).decode()
    sock.close()
    

 

posted on 2016-01-02 14:14  蒋乐兴的技术随笔  阅读(254)  评论(0编辑  收藏  举报

导航