python 学习笔记_2 模拟socket编程 服务端、客户端通信(参考核心编程2代码实现)

时间:2021-03-20 07:24:47

服务器端代码实现:

#!/usr/bin/env python
#coding=gbk
'''
接收客户端字符串,在字段串前面打上当前时间,然后返回
server端采用 python2 linux下调试运行
客户端采用python3 windows下调试运行(注意编码格式)
'''

from socket import *
from time import ctime

buf=1024

sock_serv=socket(AF_INET,SOCK_STREAM)
sock_serv.bind(('103.20.2221.183',1234))
sock_serv.listen(5)

while 1:
    print('server is listening..')
    sock_client,addr=sock_serv.accept()
    print('connect from:',addr)

while 1:
        data=sock_client.recv(buf)
        if not data:
            break
        sock_client.send('%s %s'%(ctime(),data))
    sock_client.close()
    sock_serv.close()

客户端代码实现:

#coding=gbk
from socket import *
from time import ctime

buf=1024

sock_client=socket(AF_INET,SOCK_STREAM)

sock_client.connect(('103.20.2221.183',1234))

while 1:
    data=input('please input something:')
    if not data:
        break
    sock_client.send(data.encode('gbk'))
    data=sock_client.recv(buf)
    print('receive success:%s'%data.decode('gbk'))
sock_client.close()