IOS smallSocket and python - python

I'm working on an IOS app.
I'm starting with a python server on mac that should connect to an iphone and print data sent from iphone.
the connection seems to be established but python print infinite " b " " as data... I don't know why.
the strange thing is that it happens also with cocoaAsynchronousSocket
this is the server
#!/usr/bin/python
import time
import socket
import sys
addr = sys.argv[1]
port = 4444
if not addr :
print ("No host address specified, plese specify an address", files=sys.stderr)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print ("connecting...")
try:
sock.connect ((addr, port))
except socket.error:
print ("unable to connect to", addr)
sys.exit(0)
print ("Connected to", addr)
while 1:
data = sock.recv(0)
data2 = sock.recv(1)
# if not data: break
print (data)
print (data2)
and this is some code that i use to create the connection
- (IBAction)openPressed:(id)sender {
socket = [Socket socket];
[socket listenOnPort:4444];
[socket acceptConnection];
[socket writeString:#"connection accepted"];
}

Why did u add this line:
data = sock.recv(0)
Besides that, your sever, while client might be a better name, seems good.
If it doesn't print what you expect, I suggest that you use some sniffer tools, like wireshark, to check what it really receives.

Related

Python socket client works only for one iteration

I am trying to implement sockets with python.the following code works well without the while loop..but with the while loop, for the second iteration , it gets stuck in s.sendall().could you please suggest how to fix this ?
def main():
host = socket.gethostname()
port = 11111
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
print "Connected to Server!"
while True:
print "Enter your Command:"
command = raw_input()
if(command):
try:
sock.sendall(repr(command))
except socket.error:
print "Socket Error Occured"
data = sock.recv(1024)
if data:
print('Received', repr(data))
else:
print "No Data"
else:
os.system("clear")
sock.close()
if __name__ == "__main__":
main()
Hello
I don't have all the information I need to make this post as
informed as I'd like, however I can make some educate
d guesses and try my best to explain what I think is going wrong. Are you ready?? Lets get into it.
So,
You start off by making a tcp socket and then connecting to a server hosted locally on port 11111
host = socket.gethostname()
port = 11111
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
next you enter a loop
while True:
#input command, request eval
Here your goal is to take user input and send it to a server to eval. You do that with
#get user input
print "Enter your Command:"
command = raw_input()
#send command to server for eval
sock.sendall(repr(command))
#receive then print eval
data = sock.recv(1024)
print('Received', repr(data))
this works and sends commands as you'd expect, although sending repr(command) might not be what you want to send
command = "1+1"
eval(command)
//2
eval(repr(command))
//'1+1'
Now
Here is where I have to make some assumptions
Early on you connected to a server
sock.connect((host, port))
I'm assuming that the server accepts your connection evals your command and sends the answer back. Something like
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind('localhost',11111)
sock.listen()
while True:
conn, addr = sock.accept()
command = conn.recv(1024)
sock.sendall(eval(command))
If this is the case then your connection might fail because your eval server runs eval once and then accepts a new connection.
That means that your client can no longer send to, or recieve data from, the server
I hope this helps.

Python could not receive from server after sending message over

I am currently working on my assignment and I am using python socket to connect through terminal. However, I encountered a problem where after I send my message to the server and try to receive its reply, it kind of hangs. My codes are as follows:
import socket
import sys
import md5
import re
hostname = "cs2107.spro.ink"
ip = socket.gethostbyname(hostname)
port = 9000
server_address = (ip, port)
bufferSize = 1024
# Socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print >>sys.stderr, 'connecting to %s port %s' % server_address
s.connect((ip, port))
try:
while True:
data = s.recv(bufferSize)
if not data:
break
print data
regex = re.compile(r'\n([0-9a-fA-F]+)(?:\n)', re.I | re.S | re.M)
checkHex = re.findall(regex, data)
if len(checkHex) != 0:
receiveHex = str(checkHex).strip("['']")
decode = receiveHex.decode()
m = md5.new()
m.update(decode)
hexReply = m.hexdigest()
s.sendall(hexReply.encode())
print hexReply
finally:
print >>sys.stderr, 'closing socket.....'
s.close()
The output is shown in the link: output. After I kill it, it says the most recent call is `data = s.recv(bufferSize) link: after killing the terminal. Anyone have any idea how to solve this? Appreciate your help!
The line s.recv(bufferSize) is still waiting for some incoming data from the server. However the server sends nothing more than what you see. Try to reply to the server with your hexReply variable and see what happens. Just insert s.send(hexReply + "\r\n") after the print statement.

multiclient server that receives a file from few sources

I'm building a torrent like program for a project. I want to get a file from few sources and then merge it together. the code below is my server and client for the data transfer (note: in the main program these codes are threads). variables such as address, port, directories, filename, numofclients etc are just placeholders.
The problem I'm having is that half of the time, when a client connects, the server doesn't register him (meaning it doesn't give the client info it needs to continue the sending process). when this happens the client side claims its connected but I dont know if this issue is serverbased or clientbased. If anyone can help me find the issue that would be great, I've been trying to fix it for days.
Another side issue is that when the client does send the data, it send it significantly slower than when using a normal basic send loop with one client. is the select bottlenecking my speed?
note: I'm using python 2.7. prints are for monitoring.
server:
import random
import select
import socket
portnum=3500
filename="Testvid.avi"
numofclients=2
datalist=[]
for i in range(0,numofclients):
datalist.append(open("C:/Users/Nitai/Desktop/Metorrent/"+filename+"-tmp"+str(i+1),'wb'))
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', portnum))
server_socket.listen(5)
s, address = server_socket.accept()
open_client_sockets = []
print "receivefile initiated"
def send_waiting_messages (wlist):
for message in messages_to_send:
(client_socket, data) = message
if client_socket in wlist:
client_socket.send(data)
messages_to_send.remove(message)
messages_to_send = []
dataindex=0
socketindex=[]
finishedcount=0
while finishedcount<numofclients:
rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets, open_client_sockets, [] )
for current_socket in rlist:
if current_socket is server_socket:
print "new client"
(new_socket,address)=server_socket.accept()
open_client_sockets.append(new_socket)
socketindex.append(new_socket)
print open_client_sockets
datatosend="IDP "+str(dataindex)+"%"+str(numofclients)
print datatosend
messages_to_send.append((new_socket,datatosend))
print "data sent"
print dataindex
dataindex+=1
else:
data=current_socket.recv(1024)
if data.find("EndPacket")!=-1:
print "connection finished"
finishedcount+=1
open_client_sockets.remove(current_socket)
else:
datalist[socketindex.index(current_socket)].write(data)
send_waiting_messages(wlist)
s.close()
print "select exited"
filewriter=open("C:/Users/Nitai/Desktop/Metorrent/"+filename+"-final",'wb')
for i in range(0,numofclients):
filewriter.write(datalist[i].read())
print "File received"
filewriter.close()
print "transfer finished"
client:
import random
import socket
import os
portnum=3500
filename="Testvid.avi"
address='10.0.0.5'
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((address, portnum))
print "connected"
data=s.recv(1024)
print "data received"
print data
index=int(data[4:data.find("%")])
print index
numofclients=int(data[data.find("%")+1:len(data)])
print numofclients
filetosend=open("C:/Users/Nitai/Desktop/"+filename,'rb')
filelength=int(os.stat("C:/Users/Nitai/Desktop/"+filename).st_size)
startpoint=(filelength/numofclients)*index
if numofclients==index+1:
print "last part sender"
endpoint=filelength
else:
endpoint=(filelength/numofclients)*(index+1)
filetosend.seek(startpoint)
print startpoint
print endpoint
while startpoint+1024<endpoint:
a=filetosend.read(1024)
s.send(a)
startpoint+=1024
l=filetosend.read(endpoint-filetosend.tell())
s.send(l)
filetosend.close()
time.sleep(3)
endpacketdata="EndPacket"
s.send(endpacketdata)
print "File sent"
s.close()
print "data transfer complete"
thanks for the help!
After the server_socket.listen(5), you have s, address = server_socket.accept() which is out of place, since the accept is to be done in the while loop.

Python How to build a *real* ip address multi-client server

let's say I have a multi-client server socket and a client socket in python.
Server: (You don't have to read all of the server's code, just know it's a multi-client server.
import socket, select
CONNECTION_LIST = [] # list of socket clients
RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
PORT = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this has no effect, why ?
RealServerIP = ? # I want to have a real server ip which would let me connect to the server from any computer around the globe...
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((RealServerIP, PORT))
server_socket.listen(10)
# Add server socket to the list of readable connections
CONNECTION_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
# Get the list sockets which are ready to be read through select
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
#New connection
if sock == server_socket:
# Handle the case in which there is a new connection recieved through server_socket
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
#Some incoming message from a client
else:
# Data recieved from client, process it
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(RECV_BUFFER)
# echo back the client message
if data:
sock.send(data)
# client disconnected, so remove from socket list
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
(example from http://www.binarytides.com/code-chat-application-server-client-sockets-python/).
And 3 clients which are the most simple clients you can imagine to yourself:
import socket # imports module named 'socket'
RealServerIP = ? # I need your help here.... read the continuation
my_socket = socket.socket() # creates new socket named 'my_socket'
my_socket.connect((RealServerIP, 5000)) # connects to the server
my_socket.send(str) # sends string to the server
data = my_socket.recv(1024)
print data # prints data
my_socket.close()
I wanted to check whether my server can comunicate with those 3 clients at the same time. So I want to make my server as a public server like a web-server of Facebook, etc.
So any computer around the world could connect to it.
So, I tried to figure out how would I store my python server socket online with a specific IP and PORT which has nothing to do with my localhost, I want it to be real! Like any chat/web server you know..
If you mean the IP which the user connect with it to the internet, I don't think there is a way to get it by socket module, But i got a way to do the same thing using requests module if this may help.
import requests
def get_ip():
url = 'https://www.cmyip.com'
user_ip = requests.get(url).content.decode("utf-8").split("My IP Address is ")[1].split(" <a class=")[0]
return user_ip
I hope this help.
Note: This was tested on python 3.4.3 and it is working fine. I don't know about 2.X versions.

How would I use these two Python chat room codes (server and client) to talk between different computers?

I've been looking for a project to do over the winter holidays and have found some people's codes for Python Chat rooms.
I have both a server script, and a client script up and working. But i can only make it work if they are on the same computer. I've tried having the client on a different computer, but i can't seem to make it work (it says it can't connect).
Here is the server code:
# Tcp Chat server
import socket, select
#Function to broadcast chat messages to all connected clients
def broadcast_data (sock, message):
#Do not send the message to master socket and the client who has send us the message
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION_LIST.remove(socket)
if __name__ == "__main__":
# List to keep track of socket descriptors
CONNECTION_LIST = []
RECV_BUFFER = 4096 #exponent of 2
PORT = 2015
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this has no effect, why ?
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.0.0", PORT))
server_socket.listen(10)
# Add server socket to the list of readable connections
CONNECTION_LIST.append(server_socket)
print ("Chat server started on port " + str(PORT))
while 1:
# Get the list sockets which are ready to be read through select
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
#New connection
if sock == server_socket:
# Handle the case in which there is a new connection recieved through server_socket
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print("Client (%s, %s) connected" % addr)
broadcast_data(sockfd, "[%s:%s] entered room\n" % addr)
#Some incoming message from a client
else:
# Data recieved from client, process it
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(RECV_BUFFER)
if data:
#broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)
broadcast_data(sock, "\r" + data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print ("Client (%s, %s) is offline" % addr)
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
Here is the code for the client:
#Chat Client
import socket, select, string, sys
NName = ""
def prompt() :
sys.stdout.write('<{0}> '.format(NName))
sys.stdout.flush()
#main function
if __name__ == "__main__":
if(len(sys.argv) < 3) :
print('Usage : python TCP_Client.py hostname port')
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try :
s.connect((host, port))
except :
print('Unable to connect')
sys.exit()
print('Connected to remote host.')
print('Enter your Nickname:')
NName = raw_input(" ")
prompt()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print ('\nDisconnected from chat server')
sys.exit()
else :
#print data
sys.stdout.write(data)
prompt()
#user entered a message
else :
msg = sys.stdin.readline()
s.send("<{0}> {1}".format(NName,msg))
prompt()
I'm not looking for any improvements over the program, i just want to know how i'm supposed to make the client connect to the server from a different computer.
Thanks,
Gibbon :)
EDIT
Okay, i realised i probably didn't have enough information here:
What I am doing at the moment:
In OSX terminal:
python /path/to/file/TCP_Server
And in another OSC terminal (On a different computer) (Replacing 'xxx.xxx...' with the computer running the server's ip addres:
python /path/to/file/TCP_Client xxx.xxx.xxx.xxx 2015
These Server/client codes are benefit and useful to learn and windows 10 u must modify smart screen, windows defender turn off.
I prefer that u can entered the 10.0.0.134/135/138 ip address with use wireless usb card and use wingIDE instead of IDLE environment of programming. Python is better than perl and is more flexibility than anothers programming like that php 7.0 I am fans of that. Go on python on azure microsoft and use for e-commerce destination.
Programming makes perfect with low level of language programming.

Categories