python socket 基本使用

Posted nevermore_29

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python socket 基本使用相关的知识,希望对你有一定的参考价值。

socket通常也叫做“套接字”,用于连接server client,是一个通信链的句柄,应用程序通常通过套接字向网络发出请求或应答网络请求。

就像python 处理file一样:

file是针对某个文件 打开-->读写-->关闭

socket是针对服务器 客户端进行 打开-->读写-->关闭

server部分:

import socket,sys
server_address=(127.0.0.1, 8000)
BUF_SIZE=1024
try:
   server_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)     #创建新的socket对象
except socket.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以元组表示
except socket.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..."

while True:
   client_sk, client_addr = server_sk.accept()
   print "connected by:", client_addr
   while True:
      data=client_sk.recv(BUF_SIZE)
      print data
      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部分:
import socket,sys
server_address=(127.0.0.1, 8000)
BUF_SIZE=1024

try:
   client_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
   print "socket create fail, error code:" + str(msg[0]) + error message: + msg[1]

client_sk.connect(server_address)
while True:
   data= raw_input(please input your sending message->)
   if not data:
      print "input data cannot be empty, please input again.."
      continue
   client_sk.sendall(data)
   recv_data = client_sk.recv(BUF_SIZE)
   print recv_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->







以上是关于python socket 基本使用的主要内容,如果未能解决你的问题,请参考以下文章

python socket 基本使用

Python网络编程之socket应用

Python基础:网络编程socket基本篇

Python--网络编程-----socket代码实例

python socket基本语法

Python asyncore socket客户端开发基本使用