-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket_helpers.py
43 lines (31 loc) · 1.06 KB
/
socket_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import socket
SOCK_CONFIG = {
'tcp': (socket.AF_INET, socket.SOCK_STREAM),
'udp': (socket.AF_INET, socket.SOCK_DGRAM),
}
def sock_send(payload, address, sock=None, socktype="udp"):
if sock is None:
sock = create_socket(socktype)
udp_ip, udp_port = convert_address(address)
sock.sendto(payload, (udp_ip, udp_port))
def create_socket(socktype='udp'):
return socket.socket(*SOCK_CONFIG[socktype])
def sock_connect(address):
server_ip, server_port = convert_address(address)
sock = create_socket("tcp")
sock.connect((server_ip, server_port))
return sock
def sock_bind(address):
waiting_ip, waiting_port = convert_address(address)
sock = create_socket()
sock.bind((waiting_ip, waiting_port))
return sock
def convert_address(address):
if isinstance(address, (unicode, str)):
udp_ip, udp_port = address.split(":")
elif len(address) == 2:
udp_ip, udp_port = address
else:
raise ValueError("Wrong address for a socket!")
udp_port = int(udp_port)
return udp_ip, udp_port