Skip to content

Instantly share code, notes, and snippets.

@nsojib
Created May 24, 2018 16:45
Show Gist options
  • Save nsojib/ddb3ab845aad7e2a2e7102fe21e0ced1 to your computer and use it in GitHub Desktop.
Save nsojib/ddb3ab845aad7e2a2e7102fe21e0ced1 to your computer and use it in GitHub Desktop.
socket utility
import sys
import socket
import StringIO
class MySocket():
def __init__(self, host='127.0.0.1', port=5578):
print 'my net socket'
self.host=host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def doconnect(self):
try:
server_address = (self.host, self.port)
self.sock.connect(server_address)
print 'connected'
except:
return False
return True
def readLine(self):
#buff = StringIO.StringIO(2048) # Some decent size, to avoid mid-run expansion
buff=""
while True:
data =self.sock.recv(1024) # Pull what it can
#buff.write(data) # Append that segment to the buffer
buff+=str(data)
#print 'buff=',buff
if '\n' in data: break # If that segment had '\n', break
return buff
def sendLn(self, txt):
try:
self.sock.send(txt+str('\n'))
self.sock.flush()
except:
return False
return True
def send(self, data):
try:
self.sock.send(data)
self.sock.flush()
except:
return False
return True
def recvall(self, count):
buf = b''
while count:
newbuf = self.sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
def close(self):
self.sock.close()
import sys
import socket
import StringIO
class MySocket():
def __init__(self, host='127.0.0.1', port=5578):
print 'my net socket'
self.host=host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def doconnect(self):
try:
server_address = (self.host, self.port)
self.sock.connect(server_address)
print 'connected'
except:
return False
return True
def readLine(self):
#buff = StringIO.StringIO(2048) # Some decent size, to avoid mid-run expansion
buff=""
while True:
data =self.sock.recv(1024) # Pull what it can
#buff.write(data) # Append that segment to the buffer
buff+=str(data)
#print 'buff=',buff
if '\n' in data: break # If that segment had '\n', break
return buff
def sendLn(self, txt):
try:
self.sock.send(txt+str('\n'))
self.sock.flush()
except:
return False
return True
def send(self, data):
try:
self.sock.send(data)
self.sock.flush()
except:
return False
return True
def recvall(self, count):
buf = b''
while count:
newbuf = self.sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
def close(self):
self.sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment