Just started learning python socket programming. I'm trying to send and receive data from a Raspberry Pi 3 using python sockets. I'm running the server program on the Raspberry Pi and the client program on my laptop running Ubuntu. Both are on the same WiFi network. The program runs and the client connects to the server, but there is no data transfer. Both the client and server do nothing. The two programs run properly if I try to run them both on the same device. Here's my code :-
Client
import socket
HOST = '172.16.31.51'
PORT = 5000
BUFSIZ = 1024
if __name__ == '__main__':
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input("Enter hostname [%s]: " %HOST) or HOST
port = input("Enter port [%s]: " %PORT) or PORT
sock_addr = (host, int(port))
client_sock.connect(sock_addr)
payload = 'GET TIME'
try:
while True:
client_sock.send(payload.encode('utf-8'))
data = client_sock.recv(BUFSIZ)
print(repr(data))
more = input("Want to send more data to server[y/n]:")
if more.lower() == 'y':
payload = input("Enter payload: ")
else:
break
except KeyboardInterrupt:
print("Exited by user")
client_sock.close()
Server
import socket
from time import ctime
PORT = 5000
BUFSIZ = 1024
ADDR = ('', PORT)
if __name__ == '__main__':
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(ADDR)
server_socket.listen(5)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
while True:
print('Server waiting for connection...')
client_sock, addr = server_socket.accept()
print('Client connected from: ', addr)
while True:
data = client_sock.recv(BUFSIZ)
if not data or data.decode('utf-8') == 'END':
break
print("Received from client: %s" % data.decode('utf-8'))
print("Sending the server time to client: %s" %ctime())
try:
client_sock.send(bytes(ctime(), 'utf-8'))
except KeyboardInterrupt:
print("Exited by user")
client_sock.close()
server_socket.close()
EDIT:
The screenshots - https://imgur.com/a/NgzsC
As soon as I hit Ctrl + C, on the client side, the server seems to send some data before it disconnects from the client. Here's a screenshot of that - https://imgur.com/a/hoLwN
Your sockets work OK, but you made some other programming mistakes. Did you ever run it?
This is the modified working code.
(Hint: you can start testing just the client when you use nc -l 5000 as a simple manual server.
Client
import socket
HOST = '127.0.0.1'
PORT = 5000
BUFSIZ = 1024
if __name__ == '__main__':
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = str(raw_input("Enter hostname [%s]: " %HOST)) or HOST
port = str(raw_input("Enter port [%s]: " %PORT)) or PORT
sock_addr = (host, int(port))
client_sock.connect(sock_addr)
payload = 'GET TIME'
try:
while True:
client_sock.send(payload.encode('utf-8'))
data = client_sock.recv(BUFSIZ)
print(repr(data))
more = raw_input("Want to send more data to server[y/n]:")
if more.lower() == 'y':
payload = str(raw_input("Enter payload: "))
else:
break
except KeyboardInterrupt:
print("Exited by user")
client_sock.close()
Server
import socket
from time import ctime
PORT = 5004
BUFSIZ = 1024
ADDR = ('', PORT)
if __name__ == '__main__':
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(ADDR)
server_socket.listen(5)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
while True:
print('Server waiting for connection...')
client_sock, addr = server_socket.accept()
print('Client connected from: ', addr)
while True:
data = client_sock.recv(BUFSIZ)
if not data or data.decode('utf-8') == 'END':
break
print("Received from client: %s" % data.decode('utf-8'))
print("Sending the server time to client: %s" %ctime())
try:
client_sock.send( ctime().encode('utf-8') )
except KeyboardInterrupt:
print("Exited by user")
break;
client_sock.close()
server_socket.close()
Related
I cant figure out why the client is not communicating with the Server (2 seperate jupyter notebooks with own kernel), no error messages - any suggestions?
the following code is working (without multiprocessing):
Server:
import socket
HOST = '127.0.0.1'
PORT = 50000
def start_server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen()
print ('waiting for client')
conn, addr = s.accept()
print('client connected #', addr[0], 'port:', addr[1])
return conn
Server0 = start_server()
Client:
import socket
HOST = '127.0.0.1'
PORT = 50000
data = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect_ex((HOST, PORT))
while True:
byte_message = s.recv(1024)
string_message = byte_message.decode('utf8')
header, time, data = string_message.split(' ')
if header == 'close':
s.shutdown(socket.SHUT_RDWR)
s.close()
print('client connection shut down')
header = ''
elif header == '<<':
print(time,float(data))
else:
pass
As soon as I pack the client into a function and run it as a process, client and server do not connect anymore(no error is given, and the server doesent get to this line:
print('client connected #', addr[0], 'port:', addr[1])
not working client:
import socket
import multiprocessing
HOST = '127.0.0.1'
PORT = 50000
def client():
data = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect_ex((HOST, PORT))
while True:
byte_message = s.recv(1024)
string_message = byte_message.decode('utf8')
header, time, data = string_message.split(' ')
if header == 'close':
s.shutdown(socket.SHUT_RDWR)
s.close()
print('client connection shut down')
header = ''
elif header == '<<':
print(time,float(data))
else:
pass
client_process = multiprocessing.Process(target= client)
client_process.start()
I'm trying to create a client-server file transfer using python socket but i cant make it work
For example I used this from a tutorial:
Server:
import socket, os, sys
def Main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
print(IP)
host = IP
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("from connected user: " + filename)
c.close()
if __name__ == '__main__':
Main()
Client:
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
host = '192.168.1.90'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = 'prova3.txt'
s.send('prova3.txt')
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
Now this client and server connect to each other but don't send file, what's wrong?
I have been trying to make a client-server system following this tutorial and for some reason when testing it on two different computers the two computers won't connect.
Both the UDP and the TCP code have failed, and I suspect it's because I can't figure out which IP goes to where.
Code for host:
import socket
def main():
host = 'ip.ip.ip.ip'
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
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()
Code for client:
import socket
def main():
host = 'ip.ip.ip.ip'
port = 5000
s = socket.socket()
s.connect((host, port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
data = s.recv(1024)
print("Recived from server: " + str(data))
message = raw_input("-> ")
s.close()
if __name__ == '__main__':
main()
So I found this chat program on http://www.bogotobogo.com/python/python_network_programming_tcp_server_client_chat_server_chat_client_select.php
And I want to use this at my school for me and my friends, put I don't want to chat to be ex: [192.168.1.3] "Message". I want to be able to add another argument so it shows there name they input instead of Ip. It would be a little hard to have everyone using ips. Any suggestions?
Server Code:
# chat_server.py
import sys
import socket
import select
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 9009
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
# add server socket object to the list of readable connections
SOCKET_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
# 4th arg, time_out = 0 : poll and never block
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
for sock in ready_to_read:
# a new connection request recieved
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
# a message from a client, not a new connection
else:
# process data recieved from client,
try:
# receiving data from the socket.
data = sock.recv(RECV_BUFFER)
if data:
# there is something in the socket
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + '] ' + data)
else:
# remove the socket that's broken
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
# at this stage, no data means probably the connection has been broken
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
# exception
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
for socket in SOCKET_LIST:
# send the message only to peer
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "__main__":
sys.exit(chat_server())
Client Code:
# chat_client.py
import sys
import socket
import select
def chat_client():
if(len(sys.argv) < 3) :
print 'Usage : python chat_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. You can start sending messages'
sys.stdout.write('[Me] '); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])
for sock in ready_to_read:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()
else :
# user entered a message
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write('[Me] '); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())
I got problems with making a Python socket server receive commands from a Python socket client. The server and client can send text to each other but I can't make text from the client trigger an event on the server. Could any one help me? I'm using Python 3.4.
server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
response = input("Reply: ")
if data == "dodo":
print("hejhej")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()
In server.py I tried to make the word "dodo" trigger print("hejhej").
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
data = s.recv(1024)
print("Recieved: "+(data.decode('utf-8')))
response = input("Reply: ")
if response == "exit":
break
s.sendall(response.encode('utf-8'))
s.close()
Everything here works fine but, maybe not the way you want it to. If you switch the order on a couple of the lines it will display your event string before you enter your server response.
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes: break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
if data == "dodo": # moved to before the `input` call
print("hejhej")
response = input("Reply: ")
if response == "exit":
break
conn.sendall(response.encode('utf-8'))
conn.close()