品易云推流 关闭
文章详情页
文章 > Python基础教程 > python套接字编程的服务器和客户端

python套接字编程的服务器和客户端

python套接字

头像

小妮浅浅

2021-09-13 09:32:442181浏览 · 0收藏 · 0评论

1、服务器可以是程序、计算机或专门用于管理网络资源的设备。使用socket.socket()方法创建服务器端套接字符。

服务器可以在同一个设备或计算机上,也可以在本地连接到其他设备和计算机,甚至可以远程连接。有各种类型的服务器,如数据库服务器、网络服务器、打印服务器等。

服务器通常使用socket.socket()、socket.bind()、socket.listen()等方法来建立连接并绑定到客户端。

设置套接字的第一个必要条件是导入套接字模块。

import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),1234))          
#port number can be anything between 0-65535(we usually specify non-previleged ports which are > 1023)
s.listen(5)
 
while True:
    clt,adr=s.accept()
    print(f"Connection to {adr}established")  
   #f string is literal string prefixed with f which
   #contains python expressions inside braces
    clt.send(bytes("Socket Programming in Python","utf-8 ")) #to send info to clientsocket

2、客户端是从服务器接收信息或服务的计算机或软件。导入套接字模块,创建套接字。

在客户端服务器模块中,客户端从服务器请求服务。最好的例子是Web浏览器,比如GoogleChrome,Firefox等等。这些Web浏览器要求用户向Web服务器指示所需的网页和服务。其它例子包括在线游戏,在线聊天等等。

为了在客户端和服务器之间创建连接,您需要通过指定的方法(主机和端口)使用connect()。

注意:当客户端和服务器位于同一台计算机上时,使用gethostname。

import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 2346))
msg=s.recv(1024)
print(msg.decode("utf-8"))

以上就是python套接字编程的服务器和客户端的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图