Python socket TCP服务器/客户端 + UDP 发送端/接收端
程序员文章站
2022-04-24 14:13:41
...
'''
socket
'''
import socket
def tcp_server():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('0.0.0.0',9999))
s.listen()
print(socket.gethostbyname(socket.gethostname()),9999,'server starting ......')
while True:
try:
client,addr = s.accept()
recv = client.recv(1024).decode()
print(addr[0],addr[1],'>>',recv)
client.send(recv.encode())
except:
print(addr[0],addr[1],'>>','say goodby')
def tcp_client():
while True:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((socket.gethostbyname(socket.gethostname()),9999))
text = input('send:').encode()
s.send(text)
response = s.recv(1024).decode()
print(response)
s.close()
def udp_recver():
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip = socket.gethostbyname(socket.gethostname())
port = int(input('\ninput your recver port please:'))
s.bind((ip,port))
print(ip,port,'listening......')
data,addr = s.recvfrom(1024)
print(addr,':',data.decode())
s.sendto(data,addr)
def udp_sender():
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip = input('input target ip please:')
port = int(input('input target port please:'))
text = input('send:').encode()
s.sendto(text,(ip,port))
data,addr = s.recvfrom(1024)
print(data.decode())
def select_type():
return tcp_client()
if __name__ == '__main__':
select_type()
推荐阅读
-
Asp.net Socket客户端(远程发送和接收数据)
-
python使用socket向客户端发送数据的方法
-
python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
-
java之Scoket 客户端和服务器的发送与接收
-
java之Scoket 客户端和服务器的发送与接收
-
Python实现基于TCP UDP协议的IPv4 IPv6模式客户端和服务端功能示例
-
网络套接字socket,利用UDP协议实现服务器与客户端通信
-
Socket 通信原理(Android客户端和服务器以TCP&&UDP方式互通)
-
Socket学习笔记(一):python通过socket实现客户端到服务器端的文件传输
-
python之socket(三)实现ftp客户端和服务器收发文件及md5加密文件