Python网络编程之最简单服务器与客户端的实现

Python编程语言提供了低级别的网络服务支持基本的Socket,它提供了标准的BSD Sockets API,可以访问底层操作系统Socket接口的全部方法。应用程序通常通过”套接字”向网络发出请求或者应答网络请求,使主机间或者一台计算机上的进程间可以通讯。

一、 服务器

#!/usr/bin/env python3

import socket
import time

server = socket.socket()
host = socket.gethostname()
port = 8080
server.bind((host, port))
server.listen(5)

while True:
    client, addr = server.accept()
    print('Client address:', addr)
    client.send(time.asctime().encode('UTF-8'))
    client.close()

二、 客户端

#!/usr/bin/env python3

import socket

s = socket.socket()
host = socket.gethostname()
port = 8080
s.connect((host, port))
print(s.recv(1024).decode('UTF-8'))

三、运行结果

[ycxie@fedora Workspace]$ ./server.py
Client address: ('192.168.226.129', 37130)
Client address: ('192.168.226.129', 37132)
Client address: ('192.168.226.129', 37134)
Client address: ('192.168.226.129', 37136)
Client address: ('192.168.226.129', 37138)
[ycxie@fedora Workspace]$ ./client.py
Sun Aug 12 00:32:38 2018
[ycxie@fedora Workspace]$ ./client.py
Sun Aug 12 00:32:40 2018
[ycxie@fedora Workspace]$ ./client.py
Sun Aug 12 00:32:41 2018
[ycxie@fedora Workspace]$ ./client.py
Sun Aug 12 00:32:42 2018
[ycxie@fedora Workspace]$ ./client.py
Sun Aug 12 00:32:43 2018

乍一看,确实比C语言简洁不少,有空来学习学习Python网络编程~~

Leave a Reply

Your email address will not be published. Required fields are marked *