Python 网络编程

服务器端:
#!/usr/bin/python
#Filename: myserv.py
import struct
import socket
host = '192.168.1.50'
port = 8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn,addr = s.accept()
print 'Connected by',addr
while 1:
        data = conn.recv(1024)
        print len(data)
        if not data: break
        else:
          print data
          print struct.calcsize('icc')
          s = struct.unpack('iIQ7s', data)//实现批量发布
          #s = struct.unpack('icc', data)
          print 'Recv data:',s
          print s[0]
          print s[1]
          print s[2]
          print s[3]
conn.close()
客户端 :
#!/usr/bin/python
#Filename: struct.py
import os
import struct
import socket
import time
host = "192.168.1.48"
port = 4002
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
ss = struct.pack('IIIII32s32s32s',0,96,0,0,0,'dongying','123456','1001')
#tt = struct.pack('sss','dongying','1234567','1001')
print ss
s.send(ss)
time.sleep(10)
s.close()
print 'Finish program'
[color="#ffffff"]struct -- Interpret strings as [color="#ffffff"]packed binary data。
批量发布时,对应的关系为:
Format
C Type
Python
Notes
x
pad byte
no value
c
char
string of length 1
b
signed char
integer
B
unsigned char
integer
h
short
integer
H
unsigned short
integer
i
int
integer
I
unsigned int
long
l
long
integer
L
unsigned long
long
q
long long
long
(1)
Q
unsigned long long
long
(1)
f
float
float
d
double
float
s
char[]
string
p
char[]
string
P
void *
integer