summaryrefslogtreecommitdiffstats
path: root/notFinishedCode/client.py
blob: 81f52318fdcc985207011ff07379c1be280dd3c3 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import socket
import sys
import os
import string 

class Connection:
	def __init__(self, h, p):
		self.host = h
		self.port = p
		self.s = None
		self.connected = 0

	def connect(self):
		self.s = None
		
		alive = self.ping()		
		if alive == 0:
			return 'The machine is not alive'
		for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
			af, socktype, proto, canonname, sa = res
		    	try:
		        	self.s = socket.socket(af, socktype, proto)
				self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #this resolves the bug with live packets
		    	except socket.error, msg:
		        	self.s = None
				self.connected = 0
		        	continue
		    	try:
		        	self.s.connect(sa)
		    	except socket.error, msg:
		        	self.s.close()
				self.connected = 0
		        	self.s = None
		        	continue
		    	break
		if self.s is None:
			self.connected = 0
			return 'Could not open socket'
		else: 
			self.connected = 1
			return 'Connected'

	def sendData(self, data):
		if self.connected == 1:
			self.s.send(data)

	def receiveData(self):
		if self.connected == 1:
			return self.s.recv(1024)
		else:
			return 'Not connected'

	def closeConnection(self):
		if self.connected == 1:
			self.s.close()
			self.connected = 0
		return 'Closed'

	def ping(self):
		ping_cmd = os.popen('ping '+ self.host + ' -c 1 -W 1').read()
		pingAlive = int(string.find(ping_cmd, '1 received'))
		if pingAlive != -1:
			return 1
		else: 
			return 0

#MAIN PART 
x = Connection('132.230.4.60',50008)
print x.connect()
x.sendData('hello server :)')
print x.receiveData()
x.sendData('I send you another message')
x.closeConnection()