socket通常也叫做“套接字”,用于连接server client,是一个通信链的句柄,应用程序通常通过套接字向网络发出请求或应答网络请求。
就像python 处理file一样:
file是针对某个文件 打开-->读写-->关闭
socket是针对服务器 客户端进行 打开-->读写-->关闭
server部分:
importsocket,sys
server_address=('127.0.0.1', 8000)
BUF_SIZE=1024
try:
server_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建新的socket对象exceptsocket.error, msg:print "socket create fail, error code:" + str(msg[0]) + 'error message:' + msg[1]print 'socket create successfully'
try:
server_sk.bind(server_address) #绑定server地址,address取决于地址族,AF_INET以元组表示exceptsocket.error, msg:print "socket bind address error:" + str(msg[0]) + 'error mssage:' + msg[1]print 'socket bind address successfully'server_sk.listen(5)print "listening..."
whileTrue:
client_sk, client_addr=server_sk.accept()print "connected by:", client_addrwhileTrue:
data=client_sk.recv(BUF_SIZE)printdata
client_sk.sendall(data)
server_sk.close()
参数一:地址簇
socket.AF_INET IPv4(默认)
socket.AF_INET6 IPv6
参数二:类型
socket.SOCK_STREAM 流式socket , for TCP (默认)
socket.SOCK_DGRAM 数据报式socket , for UDP
Client部分:
importsocket,sys
server_address=('127.0.0.1', 8000)
BUF_SIZE=1024
try:
client_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)exceptsocket.error, msg:print "socket create fail, error code:" + str(msg[0]) + 'error message:' + msg[1]
client_sk.connect(server_address)whileTrue:
data= raw_input('please input your sending message->')if notdata:print "input data cannot be empty, please input again.."
continueclient_sk.sendall(data)
recv_data=client_sk.recv(BUF_SIZE)printrecv_data
client_sk.close()
server 输出:
socket create successfully
socket bind address successfully
listening...
connected by: ('127.0.0.1', 63388)
aa
client 输出:
please input your sending message->aa
aa
please input your sending message->