#Socket client example in pythonimportsocket#for sockets#create an AF_INET, STREAM socket (TCP)s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)print'Socket Created'
Python 提供了一个简单的函数
socket.gethostbyname
来获得远程主机的 IP 地址:
host='www.google.com'port=80try:remote_ip=socket.gethostbyname(host)exceptsocket.gaierror:#could not resolveprint'Hostname could not be resolved. Exiting'sys.exit()print'Ip address of '+host+' is '+remote_ip
现在我们知道了服务器的 IP 地址,就可以使用连接函数
connect
连接到该 IP 的某个特定的端口上了,下面例子连接到 80 端口上(是 HTTP 服务的默认端口):
#Connect to remote servers.connect((remote_ip,port))print'Socket Connected to '+host+' on ip '+remote_ip
运行该程序:
$ python client.py
Socket created
Ip of remote host www.google.com is 173.194.38.145
Socket Connected to www.google.com on ip 173.194.38.145
上面说明连接到 www.google.com 已经成功了,接下面我们可以向服务器发送一些数据,例如发送字符串
GET / HTTP/1.1\r\n\r\n
,这是一个 HTTP 请求网页内容的命令。
#Send some data to remote servermessage="GET / HTTP/1.1\r\n\r\n"try:#Set the whole strings.sendall(message)exceptsocket.error:#Send failedprint'Send failed'sys.exit()print'Message send successfully'
发送完数据之后,客户端还需要接受服务器的响应。
函数
recv
可以用来接收 socket 的数据:
#Now receive datareply=s.recv(4096)printreply
一起运行的结果如下:
Socket created
Ip of remote host www.google.com is 173.194.38.145
Socket Connected to www.google.com on ip 173.194.38.145
Message send successfully
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html;charset=UTF-8
Location: http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ
Content-Length: 262
Date: Thu, 11 Dec 2014 08:47:58 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic,p=0.02
<HTML><HEAD><meta http-equiv="content-type"content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ">here</A>.
</BODY></HTML>
importsocketimportsysHOST=''# Symbolic name meaning all available interfacesPORT=8888# Arbitrary non-privileged ports=socket.socket(socket.AF_INET,socket.SOCK_STREAM)print'Socket created'try:s.bind((HOST,PORT))exceptsocket.error,msg:print'Bind failed. Error Code : '+str(msg[0])+' Message '+msg[1]sys.exit()print'Socket bind complete'
importsocketimportsysHOST=''# Symbolic name meaning all available interfacesPORT=8888# Arbitrary non-privileged ports=socket.socket(socket.AF_INET,socket.SOCK_STREAM)print'Socket created'try:s.bind((HOST,PORT))exceptsocket.error,msg:print'Bind failed. Error Code : '+str(msg[0])+' Message '+msg[1]sys.exit()print'Socket bind complete's.listen(10)print'Socket now listening'#wait to accept a connection - blocking callconn,addr=s.accept()print'Connected with '+addr[0]+':'+str(addr[1])#now keep talking with the clientdata=conn.recv(1024)conn.sendall(data)conn.close()s.close()
importsocketimportsysHOST=''# Symbolic name meaning all available interfacesPORT=5000# Arbitrary non-privileged ports=socket.socket(socket.AF_INET,socket.SOCK_STREAM)print'Socket created'try:s.bind((HOST,PORT))exceptsocket.error,msg:print'Bind failed. Error Code : '+str(msg[0])+' Message '+msg[1]sys.exit()print'Socket bind complete's.listen(10)print'Socket now listening'#now keep talking with the clientwhile1:#wait to accept a connection - blocking callconn,addr=s.accept()print'Connected with '+addr[0]+':'+str(addr[1])data=conn.recv(1024)reply='OK...'+dataifnotdata:breakconn.sendall(reply)conn.close()s.close()
importsocketimportsysfromthreadimport*HOST=''# Symbolic name meaning all available interfacesPORT=8888# Arbitrary non-privileged ports=socket.socket(socket.AF_INET,socket.SOCK_STREAM)print'Socket created'#Bind socket to local host and porttry:s.bind((HOST,PORT))exceptsocket.error,msg:print'Bind failed. Error Code : '+str(msg[0])+' Message '+msg[1]sys.exit()print'Socket bind complete'#Start listening on sockets.listen(10)print'Socket now listening'#Function for handling connections. This will be used to create threadsdefclientthread(conn):#Sending message to connected clientconn.send('Welcome to the server. Type something and hit enter\n')#send only takes string#infinite loop so that function do not terminate and thread do not end.whileTrue:#Receiving from clientdata=conn.recv(1024)reply='OK...'+dataifnotdata:breakconn.sendall(reply)#came out of loopconn.close()#now keep talking with the clientwhile1:#wait to accept a connection - blocking callconn,addr=s.accept()print'Connected with '+addr[0]+':'+str(addr[1])#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.start_new_thread(clientthread,(conn,))s.close()
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Welcome to the server. Type something and hit enter
OK...hi
OK...asd
OK...cv
要结束 telnet 的连接,按下
Ctrl-]
键,再输入
close
命令。
服务器终端的输出可能是这样的:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60730
Connected with 127.0.0.1:60731