tcp

服务端:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 10021))
s.listen(1)                      
                               
def tcp_connect(sock, addr):
    data = sock.recv(1024)
    print(data)
    sock.close()

while True:
    sock, addr = s.accept()
    tcp_connect(sock, addr)

客户端:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 10021))
data = raw_input("send:")
s.send(data.encode())
s.close()

udp

服务端:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('127.0.0.1', 10021))

while True:                                          
    data, addr = s.recvfrom(1024)
    print(data)
    s.sendto(data.decode('utf-8').upper().encode(), addr)

客户端:

#!/usr/bin/python
# -*- coding: utf-8 -*-


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
 
addr = ('127.0.0.1', 10021)

while True:
    data = raw_input('send:')
    if data == 'quit':
        break

    s.sendto(data.encode(), addr)
    recvdata, addr = s.recvfrom(1024)
    print(recvdata.decode('utf-8'))

s.close()

参考文章

python下的tcp
python 报错:str=input() File "", line 1, in NameError: name 'hello' is not defined
Python TCP和UDP编程例子


txgcwm
764 声望71 粉丝

Linux C/C++