python如何创建TCP服务端和客户端
程序员文章站
2022-07-04 23:06:15
本文实例为大家分享了python创建tcp服务端和客户端的具体代码,供大家参考,具体内容如下
1.服务端server
from socket import *...
本文实例为大家分享了python创建tcp服务端和客户端的具体代码,供大家参考,具体内容如下
1.服务端server
from socket import * from time import ctime host = '' port = 9999 bufsiz = 1024 addr = (host, port) tcpsersock = socket(af_inet, sock_stream) #创建套接字 tcpsersock.bind(addr) #绑定ip和端口 tcpsersock.listen(5) #监听端口,最多5人排队 while true: print('waiting for connection...') tcpclisock, addr = tcpsersock.accept() #建立连接 print('...connected from:', addr) while true: data = tcpclisock.recv(bufsiz) if not data: break content = '[%s] %s' % (bytes(ctime(), "utf-8"), data) print(data) print(type(content)) tcpclisock.send(content.encode("utf-8")) tcpclisock.close() tcpsersock.close()
2.客户端client
from socket import * host = '127.0.0.1' # or 'localhost' port = 9999 bufsiz = 1024 addr = (host, port) tcpclisock = socket(af_inet, sock_stream) tcpclisock.connect(addr) while true: data = input('> ') if not data: break tcpclisock.send(data.encode("utf-8")) data = tcpclisock.recv(bufsiz) if not data: break print(data.decode("utf-8")) tcpclisock.close()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Ruby中字符串左侧补零方法实例
下一篇: realloc 用方法