Python socket issue when connecting to raspberry pi - python

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

Related

WinError 10061 when trying to connect to socket

In Python, I made a client.py and server.py with some simple socket code.
server.py:
import socket
HEADERSIZE = 10
PORT = 1235
ADDR = "192.168.198.1" # this is my local IP found from ipconfig in cmd
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ADDR, PORT))
s.listen(5)
while True:
client, address = s.accept()
print(f'Connection from {address} established')
msg = "Hello Client"
msg = f'{len(msg):<{HEADERSIZE}}'+msg
client.send(bytes(msg, "utf-8"))
client.py:
import socket
HEADERSIZE = 10
ADDR = "67.xxx.xxx.xx" # my public IP found from whatsmyip.com
PORT = 1235
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ADDR, PORT))
while True:
full = ''
new = True
while True:
msg = s.recv(16)
if new:
msglen = int(msg[:HEADERSIZE])
new = False
full += msg.decode("utf-8")
if len(full) - HEADERSIZE == msglen:
new = True
full = ''
print(full)
Previously, I had the addresses in both programs set to socket.gethostname() because I was working on my computer only. When I sent the client to my friend to test it out with the updated information you see here, I get this error code:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
The same thing happens when I run it on my computer.
I'm very new to sockets / networking, so I apologize if I'm missing something obvious, but I've been having issues with this and any help is appreciated

Restart or cancel input() [Python]

I want to restart the input('CLIENT >> ') when the client recieves a message from the server and the same for the server (the server and client being python scripts in this case)
client.py:
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
print('Connecting to ', host, port)
s.connect((host, port))
while True:
msg = input('CLIENT >> ')
s.send(msg.encode())
msg = str(s.recv(1024))
print('SERVER >> ', str(msg))
server.py:
import socket
s = socket.socket()
host = ''
port = 12345
print('Server started!')
print('Waiting for clients...')
s.bind((host, port))
s.listen(5)
c, addr = s.accept()
print('Got connection from', addr)
while True:
recieved = c.recv(1024)
print('\n', addr, ' >> ', str(recieved))
msg = input('SERVER >> ')
c.send(msg.encode())
NOTES:
Using my laptop to run both of these scripts, I don't have an actual server in real life
Python Version: 3.8
OS: Windows 10
Editor: PyCharm Community Edition
I don't understand what restarting input means...
If you mean to show messages while 'writing messages' in the input then consider learning about threads, and spin off a thread to get messages from the server/client and print to the screen.

can't connect to local host 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")

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.

Python Logging for TCP server

I am having some problems adding in a logging file for my python TCP server code.
I've looked at some examples, but as I don't have much experience in writing my own scripts/codes, I'm not very sure how to go about doing this. I would appreciate if someone could guide me in the right direction with explanation and some examples if possible.
I am using HERCULES SETUP UTILITY , which acts as my TCP client, while my visual studio python code acts as a SERVER. My SERVER can receive the data which is sent by the client by now , I just can't seem to add in a logging file which can save the sent data into text file.Can someone please show me some examples or referance please? Your help would mean alot. This is my code so far :
from socket import *
import thread
BUFF = 1024 # buffer size
HOST = '172.16.166.206'# IP address of host
PORT = 1234 # Port number for client & server to recieve data
def response(key):
return 'Sent by client'
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF) # receive data(buffer).
print 'data:' + repr(data) #Server to recieve data sent by client.
if not data: break #If connection is closed by client, server will break and stop recieving data.
print 'sent:' + repr(response('')) # respond by saying "Sent By Client".
if __name__=='__main__':
ADDR = (HOST, PORT) #Define Addr
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and port number)
serversock.listen(0)
while 1:
print 'waiting for connection...'
clientsock, addr = serversock.accept()
print '...connected from:', addr #show its connected to which addr
thread.start_new_thread(handler, (clientsock, addr ))
In context, maybe something like this?
#!/usr/local/cpython-2.7/bin/python
import socket
import thread
BUFF = 1024 # buffer size
HOST = '127.0.0.1'
PORT = 1234 # Port number for client & server to recieve data
def response(key):
return 'Sent by client'
def logger(string, file_=open('logfile.txt', 'a'), lock=thread.allocate_lock()):
with lock:
file_.write(string)
file_.flush() # optional, makes data show up in the logfile more quickly, but is slower
def handler(clientsock, addr):
while 1:
data = clientsock.recv(BUFF) # receive data(buffer).
logger('data:' + repr(data) + '\n') #Server to recieve data sent by client.
if not data:
break #If connection is closed by client, server will break and stop recieving data.
logger('sent:' + repr(response('')) + '\n') # respond by saying "Sent By Client".
if __name__=='__main__':
ADDR = (HOST, PORT) #Define Addr
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and port number)
serversock.listen(0)
while 1:
logger('waiting for connection...\n')
clientsock, addr = serversock.accept()
logger('...connected from: ' + str(addr) + '\n') #show its connected to which addr
thread.start_new_thread(handler, (clientsock, addr))
HTH
It sounds to me like your question would be better rephrased as “How do I read and write files within Python?”.
This is something well documented at: http://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files
Example:
f = open('/tmp/log.txt', 'a')
f.write('Doing something')
do_something()
f.write('Other stuff')
other_stuff()
f.write('All finished')
f.close()

Categories

Resources