[Python开发] python使用socket通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LiJiancheng0614/article/details/45200775

这里主要整理一下python官网给的sample:https://docs.python.org/3/library/socket.html
官网给出了支持IPv4的tcp代码,这里也给出udp的代码,两者基本类似。

  • tcp_server.py
# Echo server program
from socket import *
from time import ctime

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpServerSocket = socket(AF_INET, SOCK_STREAM)
tcpServerSocket.bind(ADDR)
tcpServerSocket.listen(5)

while True:
    print('waiting for connection...')
    tcpClientSocket, address = tcpServerSocket.accept()
    print('...connected by', address)

    while True:
        data = tcpClientSocket.recv(BUFSIZE).decode()
        print(data)
        if not data:
            break
        tcpClientSocket.send(('[%s] %s' % (ctime(), data)).encode())

    tcpClientSocket.close()
tcpServerSocket.close()
  • tcp_client.py
# Echo client program
from socket import *

HOST = '127.0.0.1'
PORT = 50007              # The same port as used by the server
BUFSIZE = 1024
ADDR = (HOST, PORT)

tcpClientSocket = socket(AF_INET, SOCK_STREAM)
tcpClientSocket.connect(ADDR)
print('connected to', ADDR)
while True:
    data = input('> ')
    if not data:
        break
    tcpClientSocket.send(data.encode())
    data = tcpClientSocket.recv(BUFSIZE).decode()
    if not data:
        break
    print(data)

tcpClientSocket.close()
  • udp_server.py
# Echo server program
from socket import *
from time import ctime

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpServerSocket = socket(AF_INET, SOCK_DGRAM)
udpServerSocket.bind(ADDR)

while True:
    print('waiting for message...')
    data, address = udpServerSocket.recvfrom(BUFSIZE)
    data = data.decode()
    print('...received from', address)
    print(data)
    udpServerSocket.sendto(('[%s] %s' %(ctime(), data)).encode(), address)

udpServerSocket.close()
  • udp_client.py
# Echo client program
from socket import *

HOST = '127.0.0.1'
PORT = 50007              # The same port as used by the server
BUFSIZE = 1024
ADDR = (HOST, PORT)

while True:
    udpClientSocket = socket(AF_INET, SOCK_DGRAM)
    udpClientSocket.connect(ADDR)
    data = input('> ')
    if not data:
        break
    udpClientSocket.send(('%s\r\n' % data).encode())
    data = udpClientSocket.recv(BUFSIZE).decode()
    if not data:
        break
    print(data)

udpClientSocket.close()
展开阅读全文

没有更多推荐了,返回首页