Python Socket Communication Program Example

Source: Internet
Author: User
Tags bind sleep socket socket connect in python

The built-in socket module in Python makes network programming simpler, with two small scripts to understand how clients can establish sockets with the server side.

Client code:

#clietn. py
if __name__ = = ' __main__ ': #判断是否调用自己本身, if not then __name__ for script name
Import Socket #导入我们所需的socket模块sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) #第一步是创建socket对象. Call the socket constructor socket = Socket.socket (family, type) family parameter represents the address family and can be af_inet or Af_unix. The Af_inet family includes Internet addresses, and the Af_unix family is used for interprocess communication on the same machine. Type parameters represent socket types, can be sock_stream (stream sockets) and Sock_dgram (datagram sockets)
Sock.connect (' localhost ', 7556) # Connect to the server using the socket connect method, you need to specify the server-side IP and port

Import time
Time.sleep (2)
Sock.send (' 1 ') #处理阶段, the client and server will communicate through the Send method and the Recv method
Print SOCK.RECV (1024)
Sock.close () #传输结束, the customer closes the connection by calling the Close method of the socket.

Server-side code:

#server. py
if __name__ = = ' __main__ ':
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.bind ((' localhost ', 7556)) #将socket绑定到指定地址与端口
Sock.listen (5) #使用socket套接字的listen方法接收连接请求, the parameters in parentheses specify that up to 5 clients be allowed to connect to the server. It has a value of at least 1. When a connection request is received, these requests need to be queued and the request is rejected if the queue is full.
While True:
Connection,address = Sock.accept () #服务器套接字通过socket的accept方法等待客户请求一个连接. When the Accept method is invoked, the socket will be in the "Waiting" state. When a client requests a connection, the method establishes the connection and returns to the server. The Accept method returns a tuple (connection,address) that contains two elements. The first element connection is a new socket object that the server must communicate with the customer, and the second element address is the client's Internet addresses.
Try
Connection.settimeout (5) #设置超时时间
BUF = CONNECTION.RECV (1024) #服务器和客户端通过recv方法通信 (transfer data).
When calling recv, the server must specify an integer that corresponds to the maximum amount of data that can be received through this method call. The Recv method enters the "blocked" state when it receives the data, and finally returns a string that represents the received data. If the amount of data sent exceeds the allowable recv, the data is truncated. The extra data will be buffered on the receiving end. When you call recv later, the extra data is removed from the buffer (and any other data that the customer may send since the last call to Recv).
if buf = = ' 1 ':
Connection.send (' Welcome to Python server! ') #服务器调用send and sends information to the client in string form. The Send method returns the number of characters that have been sent.
Else
Connection.send (' Please go out! ')
Except Socket.timeout:
print ' Time Out '
Connection.close () #传输结束, the Close method that the server calls the socket closes the connection.

Attached: Complete code

#!/usr/bin/env python

#clietn.py
if __name__ == '__main__':
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 7556))
import time
time.sleep(2)
sock.send('1')
print sock.recv(1024)
sock.close()

#!/usr/bin/env python

#server. py
if __name__ = = ' __main__ ':
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.bind ((' localhost ', 7556))
Sock.listen (5)
While True:
Connection,address = Sock.accept ()
Try
Connection.settimeout (5)
BUF = CONNECTION.RECV (1024)
if buf = = ' 1 ':
Connection.send (' Welcome to Python server! ')
Else
Connection.send (' Please go out! ')
Except Socket.timeout:
print ' Time Out '
Connection.close ()

Reference http://www.2cto.com/kf/201212/180187.html

http://hi.baidu.com/yobin/item/a496a13a7c141948023edc5f

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.