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

327次阅读
没有评论

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

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套接字编程的服务器和客户端的介绍,希望对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-06-16发表,共计1125字。
新手QQ群:570568346,欢迎进群讨论 Python51学习