-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysocket.py
38 lines (33 loc) · 1.16 KB
/
mysocket.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
import socket
class MySocket:
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def send(self, msg):
totalsent = 0
MSGLEN = len(msg)
self.sock.send(str(MSGLEN))
if self.sock.recv(1024)!=".":
raise RuntimeError("client did not receive length")
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def receive(self):
chunks = []
bytes_received = 0
MSGLEN = int(self.sock.recv(1024))
self.sock.send(".")
while True:
chunk = self.sock.recv(min(MSGLEN-bytes_received,1024))
chunks.append(chunk)
if MSGLEN == (bytes_received + len(chunk)):
break
else:
bytes_received += len(chunk)
return ''.join(chunks)