3254rf 发表于 2016-2-19 08:59:27

Python Socket Client及Server简单编程

本文主要介绍使用Python语言编写Socket协议Server及Client的简单实现方法。1. Python Socket编程简介Socket通常也称作"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求。三种流行的套接字类型是:stream,datagram和raw。stream和datagram套接字可以直接与TCP协议进行接口,而raw套接字则接口到IP协议。Python Socket模块提供了对低层BSD套接字样式网络的访问,使用该模块建立具有TCP和流套接字的简单服务器。2. Python Socket Server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python
# -*- coding: utf-8 -*-

from socket import *

def SocketServer():
    try:
      Colon = ServerUrl.find(':')
      IP = ServerUrl
      Port = int(ServerUrl)

      #建立socket对象
      print 'Server start:%s'%ServerUrl
      sockobj = socket(AF_INET, SOCK_STREAM)
      sockobj.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1)

      #绑定IP端口号
      sockobj.bind((IP, Port))
      #监听,允许10个连结
      sockobj.listen(10)

      #直到进程结束时才结束循环
      while True:
            #等待client连结
            connection, address = sockobj.accept( )
            print 'Server connected by client:', address
            while True:
                #读取Client消息包内容
                data = connection.recv(1024)
                #如果没有data,跳出循环
                if not data: break
                #发送回复至Client
                RES='200 OK'
                connection.send(RES)
                print 'Receive MSG:%s'%data.strip()
                print 'Send RES:%s\r\n'%RES
            #关闭Socket
            connection.close( )

    except Exception,ex:
      print ex

ServerUrl = "202.96.100.113:9999"
SocketServer()




注:需要注意的是Socket对象建立后需要加上sockobj.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1),否则会出现Python脚本重启后Socket Server端口不会立刻关闭,出现端口占用错误。
3. Python Socket Client实现代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/python
# -*- coding: utf-8 -*-

from socket import *

def SocketClient():
    try:
      #建立socket对象
      s=socket(AF_INET,SOCK_STREAM,0)

      Colon = ServerUrl.find(':')
      IP = ServerUrl
      Port = ServerUrl

      #建立连接
      s.connect((IP,int(Port)))
      sdata='GET /Test HTTP/1.1\r\n\
Host: %s\r\n\r\n'%ServerUrl

      print "Request:\r\n%s\r\n"%sdata
      s.send(sdata)
      sresult=s.recv(1024)

      print "Response:\r\n%s\r\n" %sresult
      #关闭Socket
      s.close()
    except Exception,ex:
      print ex

ServerUrl = "202.96.100.113:9999"
SocketClient()





3. 运行结果Socket Server端运行截图如下:

Socket Client端运行截图如下:


页: [1]
查看完整版本: Python Socket Client及Server简单编程