python使用socket_python socket 基本使用

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->

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值