python socket网络接口编程

python可以调用socket模块进行TCP/UDP处理。socket可以选择不同的类型,亦即为Unix线程处理的socket以及为TCP/IP协议提供给上层的处理接口。TCP/UDP都是通过socket接口建立相应的socket对象,指示接口参数处理类型有SOCK_DGRAM和SOCK_STREAM的差别,UDP是无连接的,而TCP是面向连接的,所以在处理中略有差别,TCP处理时需要通过listen接口来监听是否有TCP的握手过程发生。
UDP 服务器及客户端程序示例
服务端程序
#!/usr/bin/python3.6
import socket

BUFFER_SIZE = 1024
TARGET_ADDR = '' #表示为本地主机
TARGET_PORT = 60000
TARGET = (TARGET_ADDR,TARGET_PORT)

#AF_INET表示为网络编程socket、SOCK_DGRAM选择UDP协议模式
ss = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ss.bind(TARGET) #绑定对应的IP地址及端口号

while True:
    data,addrRsv = ss.recvfrom(BUFFER_SIZE)
    if not data:
        sys.exit(0)
    else:
        print(data)

ss.close()
客户端程序
#!/usr/bin/python3.6
import socket

ss = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
BUFFER_SIZE = 1024
TARGET_ADDR = 'IP address'
TARGET_PORT = 60000
TARGET = (TARGET_ADDR,TARGET_PORT)

while True:
    aa = input('> ') #输入相应数据
    if not aa:
        break
    #需要为字节型数据,将数据发送给相应目标IP地址及端口号
    ss.sendto(bytes(aa,'utf-8'),TARGET)
    data,addrRsv = ss.recvfrom(BUFFER_SIZE)
    if not data:
        break
    else:
        print(data)
        print(addrRsv)
    
ss.close()
TCP 服务端和客户端程序示例
服务器端程序
#!/usr/bin/python3.6
from socket import *

BUFFERSIZE = 1024
#SOCK_STREAM选择为TCP协议
s = socket(AF_INET, SOCK_STREAM) # Create TCP socket
s.bind(("",60000)) # Bind to port 60000
s.listen() # Start listening
while 1:
    client,addr = s.accept() # Wait for a connection 具有阻塞功能
    print("Got a connection from ", addr)
    client.send(b'connect successfully') 
    aa = client.recv(BUFFERSIZE)
    print(aa)
    client.close()
客户端程序
#!/usr/bin/python3.6
from socket import *

BUFFERSIZE = 1024

ss = socket(AF_INET,SOCK_STREAM) # Create TCP socket
ss.connect(("IP address",60000)) # Connect to the server
tmp = ss.recv(BUFFERSIZE) # Receive up to 1024 bytes
print(tmp)
ss.send(b"feedback")
ss.close() # Close connection

你可能感兴趣的:(python知识)