Python tcp和udp协议程序

tcp_ser.py

# -*- coding: utf-8 -*-

import socket

s = socket.socket()

host = socket.gethostname()

port = 12345

s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print "connect addr is : ", addr
    c.send("hello world")
c.close()

tcp_cli.py

# -*- coding: utf-8 -*-

import socket

s = socket.socket()

host = socket.gethostname()

port = 12345

s.connect((host, port))

print s.recv(1024)

s.close()

udp_ser.py

# -*- coding: utf-8 -*-

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

host = socket.gethostname()

port = 12345

s.bind((host, port))

while True:
    data, addr = s.recvfrom(1024)
    print "Received from %s:%s"%addr
    s.sendto("hello world", addr)

s.close()

udp_cli.py

# -*- coding: utf-8 -*-

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

host = socket.gethostname()

port = 12345

s.sendto("hello world", (host, port))

print s.recvfrom(1024)

s.close()

猜你喜欢

转载自blog.csdn.net/yuchunhai321/article/details/83541693
今日推荐