[学习笔记]Socket通信
Socket通信
base on py,by laoair
2023/3/5
客户端(sender)
创建Socket
import socket #for sockets
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket Created'
-
socket(地址簇,类型)
-
地址簇:AF_INET ---- ipv4
-
类型
- SOCK_STREAM,TCP传输控制协议
- SOCK_DGRAM ,UDP通讯协议
-
连接服务器
s.connect( (remote_ip , port) )
发送数据
-
s.sendall(message)
- message:string类型
- 返回值是发送字节的数量
#Send some data to remote server
message = "GET / HTTP/1.1\r\n\r\n"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
接收数据
-
s.recv(bufsize)
- bufsize指定最多可以接收的数量
- 数据以字符串形式返回
reply = s.recv(4096)
- 缓冲区是4096个字节
关闭
s.close()
服务器端 (recevier)
绑定 Socket
-
s.bind((HOST, PORT))
- 使用元组(host, port) 的形式表示地址
-
bind函数 本地连接
import socket
import sys
HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
监听
-
s.listen(10)
- 指定可以挂起的最大连接数量。这个参数的值最小为1,般设置为5。
- 最多同时监听10个连接
s.listen(10)
接受连接
-
conn, addr = s.accept()
- conn 是新的套接字对象,可以理解为会话实例
- addr是连接客户端的地址,内容为[ip,port]
- 一般是阻塞态
#wait to accept a connection - blocking call
conn, addr = s.accept()
#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])
接收数据
#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)
关闭
conn.close()
s.close()
服务器代码
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.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 client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
conn.close()
s.close()