首页 > 代码库 > python基础-socket通信

python基础-socket通信

socket是一种双向通信的起点和重点,氛围服务器端和客户端

Socket服务器端用到的方法有

MethodDescription
s.bind()This method binds address (hostname, port number pair) to socket.
s.listen()This method sets up and start TCP listener.
s.accept()This passively accept TCP client connection, waiting until connection arrives (blocking).

Socket客户端用到的方法有

MethodDescription
s.connect()This method actively initiates TCP server connection.

Socket通用方法有

MethodDescription
s.recv()This method receives TCP message
s.send()This method transmits TCP message
s.recvfrom()This method receives UDP message
s.sendto()This method transmits UDP message
s.close()This method closes socket
socket.gethostname()Returns the hostname.

 

下面为一个简单的socket通信的例子,包括了一个socket服务器端监听本地服务器的某一个端口,一个socket的客户端向服务器端发送请求。服务器端接收到请求之后会返回一个消息

 

socket服务器端

创建了一个简单的socket,绑定在本地服务器的端口上对外提供服务。监听到请求的时候会做出响应

s.listen表示启动监听,监听队列数为5

 1 import socket 2  3 #create a socket object,and bind it to the port 4 s=socket.socket() 5 host = socket.gethostname() 6 port = 12345 7 s.bind((host,port)) 8  9 s.listen(5)10 11 while True:12     c,addr = s.accept()13     print Got connectoion from,addr14     c.send(thank you from connecting)15     c.close()

 

socket客户端

import sockets=socket.socket()host = socket.gethostname()port = 12345s.connect((host,port))print s.recv(1024)s.close()

 

python基础-socket通信