Python 的 Socket 编程
Socket是网络应用的基础。而Python使得网络socket编程入门变得超级简单。在这篇简介里面我们将创建一个简单服务器,用于接受和相应客户端程序的请求。
由于本人最近对 Linux Containers 有点痴迷,因此我们也将在服务器中实现2个容器。同时在容器中我们在几秒钟内就能创建其他一些主机,这就能非常简单的模拟出一个网络。
创建容器
我使用的是Ubuntu14.04. 然后用root用户运行下面的命令就可以创建好2个容器了。
lxc-create -t download -n pyServer
# Choose ubuntu, trusty, amd64 when prompted
# Then clone the first container
lxc-clone -o pyServer -n pyClient
启动服务器
现在我们创建好了容器,先进入到服务器容器中并启动我们的服务器程序。用root权限运行下面这条命令就可以启动容器了:lxc-start -n pyServer -d, 这将启动容器作为我们的守护进程。让我们先重新连接进入这个容器。这里我喜欢使用screen,这样我可以很方便的进出到容器中。先创建screen会话: screen -dRR pyServer,需要重新连接到容器中的话,可以用命令:lxc-attach -n pyServer
当我们进入到容器中后,我们需要安装python并启动服务器。
apt-get install python
vim pyServer.py
打开vim(或你个人偏好的文本编辑器),敲入以下python代码。
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print "The server is ready to rock and roll!"
while 1:
name, clientAddress = serverSocket.recvfrom(2048)
response = "Hello " + str(name) + "! You are really good at socket programming"
serverSocket.sendto(response, clientAddress)
这段代码很直观。我们创建了一个serverSocket监听12000端口。当接收到请求的时候(包含用户名)就会回复一条信息。启动服务器的命令是 python pyServer.py 如果一切正常的话,你应该可以看到这样一条信息 This server is ready to rock and roll! 用Ctrl+a 和Ctrl+d退出容器(还有screen会话)
启动客户端
现在服务器端已经准备就绪,改让客户端跑起来了。在开始前先查一下服务器容器的IP地址,我们马上就会用到。你可以用这个命令得到IP:lxc-ls --fancy 。用一个screen会话进入到客户端的容器,和前面步骤一样安装好python。
lxc-start -n pyClient -d
screen -dRR pyClient
lxc-attach -n pyClient
apt-get install python
vim pyClient.py
在vim里面敲入以下代码创建一个pyClient.py文件。
from socket import *
# Replace the IP address in serverName with the IP of your container that you grabbed previously.
serverName = '10.0.3.211'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
name = raw_input('Please enter your name:')
clientSocket.sendto(name, (serverName, serverPort))
response, serverAddress = clientSocket.recvfrom(2048)
print response
clientSocket.close()
这段代码也很直观。要求用户输入用户名,然后发送到服务器,最后打印出服务器响应信息。
现在你可以自己来了!保存文件,然后执行python程序 python pyClient.py .在你输入你的名字并按下回车后,就应该可以收到一条来自服务器的响应信息。
这是一个非常简单的例子,但我们很容易就发现,可以在这些基础的代码上面做一些拓展就可以实现很多更有趣也更复杂的应用。我们还可以利用LXC强大的功能但简便的操作模拟出一个更大的网络从而实现一个分布式应用。
以上所述就是本文的全部内容了,希望对大家学习python能够有所帮助。
请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
