python socket 入门


server:

<span style="font-family:Courier New;font-size:18px;"><span style="font-family:Courier New;font-size:14px;">import socket
import sys

HOST=''
PORT=21567
BUFSIZE=1024
ADDR=(HOST,PORT)

try:
    tcpSerSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    print('socket created.')
except (socket.error,msg):
    print('failed to create socket.Error code:'+ str(msg[0]) + ' , Error message : ' + msg[1])
    sys.exit()
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)    # allow 5 connection

while True:
    print('waiting for connetion...')
    tcpCliSock,addr=tcpSerSock.accept()
    print('...connected from:',addr)

    while True:
        data=tcpCliSock.recv(BUFSIZE).decode()
        print(data)
        if not data:
            break
        tcpCliSock.send(('you typed '+data).encode())
    tcpCliSock.close()    #diff here.see python core programming
tcpSerSock.close()
</span></span>


client:

<span style="font-family:Courier New;font-size:18px;"><span style="font-family:Courier New;font-size:14px;">import socket
import sys

HOST='localhost'
PORT=21567    #must be same to server's
BUFSIZE=1024
ADDR=(HOST,PORT)

try:
    tcpCliSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    print('socket created.')
except (socket.error,msg):
    print('failed to create socket.Error code:'+ str(msg[0]) + ' , Error message : ' + msg[1])
    sys.exit()
tcpCliSock.connect(ADDR)

while True:
    data=input('>')
    if not data:    #enter to end
        break
    tcpCliSock.send(data.encode())
    data=tcpCliSock.recv(BUFSIZE).decode()    #since 'str' is different from unicodestring in python3
    if not data:    #recv err,end
        break
    print(data)
tcpCliSock.close()
</span></span>

建议在cmd下运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值