First socket programming (python)

Source: Internet
Author: User
Tags server port

Because I want to support server-side operation, I use Linux, support multiple terminals to run, if run directly on the IDE can not run both the server side and the client

1: First you need to know how to run a Python script at the terminal

$ chmod a+x helloworld.py$ ./helloworld.pyHelloWorld

The chmod command is used to change the mode of the file, giving all users in the system the permission to execute the source file. Then we can execute the program directly by specifying the location of the source file. We use./to indicate that the program is in the current directory.

2:
The Python directory must be specified in the source program, and the Python execution directory is not known with the which Python command to view
and add the path to the script.

#!/usr/bin/python

The server process first binds a port and listens for connections from other clients. If a client connects, the server establishes a socket connection to the client, and the subsequent communication is connected to the socket.

Therefore, the server opens a fixed port (for example, 80) to listen, creating the socket connection for each client connection. Because the server will have a large number of connections from the client, the server is able to differentiate between which client and which clients the socket connection is bound to. A socket relies on 4 items: server address, server port, client address, client port to uniquely identify a socket.

However, the server also needs to respond to requests from multiple clients at the same time, so each connection requires a new process or a new thread to handle, otherwise the server can only serve one client at a time.

Let's write a simple server program that receives a client connection and sends a string of strings from the client to a hello and send it back.

First, create a socket based on the IPV4 and TCP protocol:

socket.socket(socketsocket.SOCK_STREAM)

Then we want to bind the listening address and port. The server may have more than one network card, can be bound to the IP address of a network card, you can also bind to all network addresses with 0.0.0.0, you can also use 127.0.0.1 to bind to the native address. 127.0.0.1 is a special IP address that represents the native address, and if bound to this address, the client must be running at the same time in order to connect, that is, the external computer cannot connect.

The port number needs to be specified beforehand. Because we write this service is not standard service, so with 9999 this port number. Note that a port number less than 1024 must have administrator privileges to bind:

Listening Port:

S.bind (' 127.0.0.1 ', 9999)
Immediately after that, call the Listen () method to start listening on the port, and the incoming parameter specifies the maximum number of waiting connections:

S.listen (5)
Print (' Waiting for connection ... ')
Next, the server program passes a permanent loop to accept the connection from the client, and accept () waits for and returns a client connection:

while True:    # 接受一个新连接:    sock, addr = s.accept()    # 创建新线程来处理TCP连接:    t = threading.Thread(target=tcplink, args=(sock, addr))    t.start()

Each connection must create a new thread (or process) to handle, or the single thread cannot accept connections from other clients during the process of processing the connection:

 def Tcplink(sock, addr):Print' Accept new connection from%s:%s ... '% addr) Sock.send (b ' welcome! ') while True: Data = SOCK.RECV (1024x768) Time.sleep (1)if  notDataorData.decode (' Utf-8 ') ==' exit ': BreakSock.send ((' Hello,%s! '% data). Encode (' Utf-8 ')) Sock.close () print (' Connection from%s:%s closed. '% addr)

After the connection is established, the server first sends a welcome message and then waits for the client data, plus a hello to send to the client. If the client sends the exit string, the connection is closed directly.

To test this server program, we also need to write a client program:

s=Socket.Socket(Socket. Af_inet,Socket. SOCK_STREAM)# to establish a connection:s.Connect((' 127.0.0.1 ',9999))# Receive Welcome message:Print(s.recv(1024x768). Decode (' Utf-8 ')) forData in [b' Michael 'B' Tracy 'B' Sarah ']:# Send data:    s.Send(data)Print(s.recv(1024x768). Decode (' Utf-8 '))s.Send(b' exit ')s.Close()

We need to open two command-line windows, one running the server program, the other running the client program, you can see the effect:

Complete service-side program

#!/usr/bin/python#encoding: Utf-8ImportSocketImportThreadingImportTimes = Socket.socket (socket.af_inet, socket. Sock_stream) S.bind ((' 127.0.0.1 ',9999)) S.listen (5) Print (' Waiting for connection ... ') def main():     while True:# Accept a new connection:Sock, addr = S.accept ()# Create a new thread to handle the TCP connection:t = Threading. Thread (Target=tcplink, args= (sock, addr)) T.start () def Tcplink(sock, addr):Print' Accept new connection from%s:%s ... '% addr) Sock.send (b ' welcome! ') while True: Data = SOCK.RECV (1024x768) Time.sleep (1)if  notDataorData.decode (' Utf-8 ') ==' exit ': BreakSock.send ((' Hello,%s! '% data). Encode (' Utf-8 ')) Sock.close () print (' Connection from%s:%s closed. '% addr) Main ()

A complete client program

#!/usr/bin/python#encoding: Utf-8ImportSocketImport threadings=Socket.Socket(Socket. Af_inet,Socket. SOCK_STREAM)# to establish a connection:s.Connect((' 127.0.0.1 ',9999))# Receive Welcome message:Print(s.recv(1024x768). Decode (' Utf-8 ')) forData in [' Michael ',' Tracy ',' Sarah ']:# Send data:    s.Send(data)Print(s.recv(1024x768). Decode (' Utf-8 '))s.Send(b' exit ')s.Close()

Run effect
Server-side

Client

1) The system starts the server execution. The server completes some initialization operations and then goes to sleep, waiting for the client to request.
2) on a machine in the network, the user executes the client program
3) client to establish a connection to the server process
4) After the connection is established, the client sends a request to the server over the network to request a service.
5) After the server receives a request from the client, it processes the content according to the client's request, and then returns the processing result.
6) The server disconnects from the client, continues to sleep, and waits for requests from other clients.

That's it.... C + + network programming is more troublesome than Python, and it's not coming out ... Qaq
Currently the plan is to engage in the network programming under Linux during the day, to engage in ACM at night .....
Which great God has Linux C + + network programming good things can give me a message oh, very grateful

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

First socket programming (python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.