can't connect to local host python - python

Hi i made this file server app and i opened the server in one laptop, and opened the client program in another laptop but i couldn't connect to the server. both laptops are connected to same wifi so shouldn't it be working? and if i open the server and client program in one laptop, the client can connect to server.
here's my code
Server
import threading
import os
import socket
def RetrFile(name, sock):
filename = str(sock.recv(1024), 'utf-8')
print(filename)
if os.path.isfile(filename):
sock.send(bytes("EXISTS" + str(os.path.getsize(filename)), 'utf-8'))
userResponse = str(sock.recv(1024), 'utf-8')
if userResponse[:2] == 'Ok':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend=f.read(1024)
sock.send(bytesToSend)
else:
sock.send(bytes("ERR", 'utf-8'))
sock.close()
def Main():
host = socket.gethostbyname("localhost")
port = 5123
s = socket.socket()
s.bind(('0.0.0.0', port))
s.listen(5)
print("Server started")
while True:
c, addr = s.accept()
print("Client connected" + str(addr))
t = threading.Thread(target=RetrFile, args=("rthread", c))
t.start()
s.close()
Main()
Client
import socket
def Main():
host = socket.gethostbyname("localhost")
port = 5123
s= socket.socket()
s.connect((host, port))
filename = input("Filename? ->")
if filename != 'q':
s.send(bytes(filename,'utf-8'))
data=str(s.recv(1024),'utf-8')
if data[:6] == 'EXISTS':
filesze = data[6:]
message = input("File Exists" + filesze + "(Y/N)")
if message == 'Y':
s.send(bytes("Ok",'utf-8'))
f = open('new_'+filename, 'wb')
data = s.recv(1024)
total = len(data)
f.write(data)
while total < int(filesze):
data = s.recv(1024)
total+= len(data)
f.write(data)
print('%.2f' %((total/int(filesze)*100)), " percentage complted ")
print("Download Complete")
else:
print("doesnt exist")
s.close()
Main()

You seem to be misunderstanding the meaning of "localhost". It always, only refers to the exact computer you're on. So for the client, "localhost" resolves to itself, and on the server "localhost" refers to itself. Hence, the client looks for the server running on its own computer at port 5123, which of course fails because the server isn't running on its same computer, it's running somewhere else. That's also why the code works when the server and the client are both on the same machine.
You need to get the ip address or hostname of the server laptop in order to connect to it from the client. You can get this by running hostname on the server computer in a linux terminal or windows command line, and putting that name instead of "localhost" into the code that's running on the client computer.
E.g., on the server laptop in a terminal:
$ hostname
myserver
And in your client code:
host = socket.gethostbyname("myserver")

Related

sending file through socket in python 3

In the code below I've tried to send an image using the python socket module in one machine to another machine. So I have 2 files: client.py and Server.py
as I figured it out the problem is when I read the image(as bytes) at the client machine and then the server tries to receive the file, at that moment when sending process is done before the receiving process then the error below occurs at line 13 of the client code:
BrokenPipeError: [Errno 32] Broken pipe
I want to find out what this error is and why does it occur in my code.
Server.py
import socket
host = '192.168.1.35'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
while True:
conn , addr = s.accept()
data = conn.recv(1024)
with open(r"C:\Users\master\Desktop\music.jpg",'wb') as f:
f.write(data)
# conn.send(b'done')
data = conn.recv(1024)
if not data:
break
conn.send(b'done')
conn.send(b'done')
conn.close()
s.close()
Client.py
import socket
def main():
HOST = '192.168.1.35'
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
f = open('/home/taha/Desktop/f.jpg','rb')
data = f.read()
s.sendfile(f)
if s.recv(1024) == b'done':
f.close()
s.close()
if __name__ == '__main__':
main()
You are closing the server connection before the client read the โ€œdoneโ€

Python socket issue when connecting to raspberry pi

I am trying to do wireless communications between a PC (windows) and a Raspberry Pi 3 using python's socket module. The server is the PC and the client is the Pi. When I run the code (server first then client) both scripts get stuck after "hey, checking TCP socket".
When I do the reverse (Pi being the server and PC being the client) the code works fine, with data been sent correctly.
Both the PC and Pi are connected to the same network. The IP address of PC is 10.0.0.198 and the Pi is 10.0.0.63.
I think the problem is that the port is not open when I use my PC as a server. How to resolve this?
My client script:
import socket
import sys
def read(port):
s = socket.socket()
host = '10.0.0.198' #(IP address of PC (server))
s.connect((host,port))
try:
msg = s.recv(1024)
s.close()
except socket.error, msg:
sys.stderr.write('error %s'%msg[1])
s.close()
print 'close'
sys.exit(2)
return msg
if __name__ == '__main__':
port = 1025
while True:
print 'hey, checking TCP socket'
data = read(port)
print 'i just read %s' % data
print 'port num is: %d' % port
port = port + 1
My server script:
import socket
import time
def send(data, port):
s = socket.socket()
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from',addr
c.send(data)
c.close()
if __name__ == '__main__':
port = 1025
num = 1
while True:
print 'hey, sending data'
words = 'helloWorld'
data = words + str(num)
print 'send data: %s' % data
send(data,port)
port = port + 1
num = num + 1

can you access a file from a virtual machine using locust.io and perform load testing on this file

I am using locust.io for the first time. I want to access a file from a virtual machine which i have created using a get request in locust.io. I want to then simulate multiple users for this request. Is this possible using locust.io?
Basically the code below is what I want to replicate using locust.io for multiple users.
This is my code for a single client and server using sockets.
#server.py
import socket
port = 3335
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#host = socket.gethostname()
s.bind(('',port))
s.listen(5)
print("server Ready")
while True:
conn,addr = s.accept()
print("connection received from ",addr)
data = conn.recv(2048)
#print("server received",repr(data))
filename=data.decode()
f=open(filename,'rb')
l=f.read(1024)
while(l):
conn.send(l)
print('sent',repr(l))
l=f.read(1024)
f.close()
print('done sending')
#conn.send('thankyou'.encode())
conn.close()
#client.py
import socket
port = 3335
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = input("Enter the ip address of server")
s.connect((host,port))
file = input("Enter the filename")
s.send(file.encode())
while True:
print("receiving data")
data = s.recv(1024)
print("data = ",(data))
if not data:
break
print("successful")
s.close()
print("connection closed")

Windows 10 - VB 5.2.4 with Ubuntu 16.04: Sending files between two VMs with Python

I'm new to python and this time I want to send a file between two VMs, first of all, the VMs are configured with NAT Network, both VMs can ping each other. The codes are the following:
Server side:
#server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
# s.bind((host, port)) # Bind to the port
s.bind(('', port))
s.listen(5) # Now wait for client connection.
print 'Server listening....'
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='runbonesi.py'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
conn.shutdown(socket.SHUT_WR)
print conn.recv(1024)
conn.close()
client side:
#client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
#host = socket.gethostname() # Get local machine name
host = '10.0.2.15'
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('received_file', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
The results can be seen in the following pictures:
Server side:
result on server
Client side:
result on client
The problem is, the client didn't receive the file as .py format, it only received as txt files. Please help me resolve this issue.
Thank you.
After s.connect((host, port)) in the client script you have to write s.send(...) with 'hello', for example. You also forgot to write the file extension '.py' in with open(...) (only if you want to save the file as Python script!). And you also have to add s.send(...) before you close the connection on the client side. ๐Ÿ˜‰

Not able to execute the program successfully, gives "Error: Address already in use"

I am working on Networking module,making connections with client ans server.
The Server code is as follows :
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.connect()
print "Connection from: " + str(addr)
while True:
data = c.recv(1024)
if not data:
break
print "from connected user: " + str(data)
data = str(data).upper()
print "sending: " + str(data)
c.send(data)
c.close()
if __name__ == '__main__':
Main()
The Client code is as follows:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
data = s.recv(1024)
print 'Received from server: ' + str(data)
message = raw_input("-> ")
s.close()
if __name__ == '__main__':
Main()
But not able to execute the program successfully, gives the error address already in use.
Use the command netstat -nlp and find out the above mentioned port in the list.You will find the same port and the corrosponding PID also, either kill that process by kill -9 or you can go to your respective code and change the port number.
Secondly,it's preferrable to use localhost instead of '127.0.0.1'.
And there's an issue in your server code as well, instead of this statement 'c, addr = s.connect()' you need to write this one ' c, addr = s.connect()'.You need too accept the incoming connection and then connect with it.You are missing the acceptance of incoming connection.

Categories

Resources