前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python socket 服务端、客户端

python socket 服务端、客户端

作者头像
用户5760343
发布2022-05-13 10:02:52
1.2K0
发布2022-05-13 10:02:52
举报
文章被收录于专栏:sktjsktj

from socket import * # get socket constructor and constants myHost = '' # '' = all available interfaces on host myPort = 50007 # listen on a non-reserved port number

sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # listen, allow 5 pending connects

while True: # listen until process killed connection, address = sockobj.accept() # wait for next client connect print('Server connected by', address) # connection is a new socket while True: data = connection.recv(1024) # read next line on client socket if not data: break # send a reply line to the client connection.send(b'Echo=>' + data) # until eof when socket closed connection.close()

client

import sys from socket import * # portable socket interface plus constants serverHost = 'localhost' # server name, or: 'starship.python.net' serverPort = 50007 # non-reserved port used by the server

message = [b'Hello network world'] # default text to send to server # requires bytes: b'' or str,encode() if len(sys.argv) > 1: serverHost = sys.argv[1] # server from cmd line arg 1 if len(sys.argv) > 2: # text from cmd line args 2..n message = (x.encode() for x in sys.argv[2:])

sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP/IP socket object sockobj.connect((serverHost, serverPort)) # connect to server machine + port

for line in message: sockobj.send(line) # send line to server over socket data = sockobj.recv(1024) # receive line from server: up to 1k print('Client received:', data) # bytes are quoted, was x, repr(x)

sockobj.close() # close socket to send eof to server

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • client
相关产品与服务
命令行工具
腾讯云命令行工具 TCCLI 是管理腾讯云资源的统一工具。使用腾讯云命令行工具,您可以快速调用腾讯云 API 来管理您的腾讯云资源。此外,您还可以基于腾讯云的命令行工具来做自动化和脚本处理,以更多样的方式进行组合和重用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档