So I have successfully created a socket connection to one client and another, but I am having trouble getting them to switch from one another with loops, did some while true and if statements to make the program recognize when one system wants to switch based on user input but I don't think I'm doing it right. Can some one help me out with a code to switch back and forth
The following is the code I'm attempting to implement.
This is the code on my computer:
import socket,sys,os,time
T2='yourturn'
serverAddr = ('192.168.0.120', 20104)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#client.connect(serverAddr)
sock = client
client.connect(('192.168.0.120', 20104))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def redirectOut(port=20104, host='192.168.0.11'):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = client
# caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file
# make prints go to sock.send
return sock
########################################33333
time.sleep(10)
HOST = ''
PORT2 = 20105
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
l=s.bind((HOST, PORT2))
except socket.error as msg:
print('Bind failed. ')
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
print('Connected to ' + addr[0] + ':' + str(addr[1]))
####################################################
time.sleep(10)
while True:
if T2!='yourturn':
data = conn.recv(1024)
line = data.decode # convert to string (Python 3 only)
T2=print(line)
else :
if T2=='myturn':
break
else:
redirectOut()
T2=print(input())
this is the code on my begalbone black:
import socket
import sys
import os, time
HOST = ''
PORT2 = 20104
T='yourturn'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
l=s.bind((HOST, PORT2))
except socket.error as msg:
print('Bind failed. ')
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
print('Connected to ' + addr[0] + ':' + str(addr[1]))
#################################################################
time.sleep(15)
serverAddr = ('192.168.0.11', 20105)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = client
try:
sock.connect(('192.168.0.11', 20105))
fsr = 'P9_40'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except TimeoutError:
os.system('reboot')
def redirectOut(port=20105, host='192.168.0.120'):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = client
# caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file # make prints go to sock.send
return sock
##############################################################
time.sleep(10)
while True:
if T!='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8') # convert to string (Python 3 only)
T=print(line)
else:
redirectOut()
if T=='yourturn':
break
else:
T=print(input())
So tried this while loop: but its still hanging up, I think I'm close:
T2='yourturn'
while True:
#for line in 'Python':
print(T2)
time.sleep(10)
if T2=='myturn':
data = conn.recv(1024)
line = data.decode
print("myturn print")
l=print(line)
if l=="yourturn":
continue
if T2=="yourturn" or T2!='myturn':
print(T2)
print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
if k=="myturn":
T2='myturn'
continue
Tried the folowing but reciving machine is hanging up when myturn is input:
sending:
time.sleep(3)
T2='yourturn'
print('here')
while True:
#for line in 'Python':
#print(T2)
#time.sleep(10)
if T2=='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
#print("myturn print")
l=print(line)
if l=="yourturn":
T2='yourturn'
continue
if T2=="yourturn" and T2!='myturn':
#print(T2)
#print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
print(k)
if k=="myturn":
T2=print('myturn')
T2='myturn'
print('there')
continue
receiving:
time.sleep(3)
T='yourturn'
while True:
#for line in 'Python':
#print(T)
if T=='yourturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
#print("myturn print")
l=print(line)
if l=='myturn':
T='myturn'
continue
if l=='exit':
client.close()
break
if T=='myturn' and T!='yourturn':
#print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
print(k)
if k=='yourturn':
T=print('yourturn')
continue
EDIT SOLUTION:
I finally figured it out, removed my reditectOut function and opened the port with windows firewall to implement this code
my computer:
T2='yourturn'
while True:
if T2=='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
print(line)
l=line
if l=="yourturn":
T2='yourturn'
continue
if T2=="yourturn" and T2!='myturn':
k=input()
client.sendto(k.encode('utf-8'),('192.168.0.120', 20104))
if k=="myturn":
T2='myturn'
continue
Beagle bone black:
time.sleep(3)
T='yourturn'
while True:
if T=='yourturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
print(line)
l=line
if l=='myturn':
T='myturn'
continue
if T=='myturn' and T!='yourturn':
k=input()
client.sendto(k.encode('utf-8'),('192.168.0.11', 20105))
if k=='yourturn':
T='yourturn'
continue
Related
I have used Python socket in ESP as a server and Laptop as a client. I customized the socket codes from this site. When I send the loop as the client input, I enter a loop on the server. I don't know how the while loop is broken when I send a word other than loop, For example "Hello".
server.py:
import socket
host = ''
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(1)
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def Hello_():
print('Hello')
def Loop_():
while True:
print('yes')
def dataTransfer(conn):
while True:
data = conn.recv(1024)
data = data.decode('utf-8')
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'loop':
Loop_()
if command == 'Hello':
Hello_()
else:
print("X")
conn.close()
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
break
client.py
import socket
host = '192.168.56.1'
port = 5560
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while True:
command = input("Enter your command: ")
s.send(str.encode(command))
s.close()
I know your time is valuable and I appreciate your attention for spending time for help me.
If you want the Loop_() method to return when more data is received on the socket, you can modify the method so that it calls select() to poll the socket to see if more data has arrived, as shown below. (Note that I've added a conn argument to the Loop_() method so I can pass in the socket to check it)
import select
[...]
def Loop_(conn):
while True:
print('yes')
inReady, outReady, exReady = select.select([conn], [], [], 0.0)
if (conn in inReady):
print('more data has arrived at the TCP socket, returning from Loop_()')
break
def dataTransfer(conn):
while True:
data = conn.recv(1024)
data = data.decode('utf-8')
dataMessage = data.split(' ', 1)
command = dataMessage[0]
if command == 'loop':
Loop_(conn)
if command == 'Hello':
Hello_()
else:
print("X")
conn.close()
I make some program to send data from raspberry to pc using socket communication. so I want to make raspberry to keep sending data in every second via socket if my pc send command "RUN". and stop if my pc send command "STOP".
client.py
.
.
.
def setupSocket():
try :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
return s,'CONNECT'
except socket.error as msg:
print(msg)
def sendReceive(s, message):
try:
s.send(str.encode(message))
reply = s.recv(1024)
reply = reply.decode('utf-8')
print(reply)
return reply
except:
return 'ERR'
if __name__=='__main__':
s = setupSocket()
while True:
data = sendReceive(s,'GET')
sleep(1)
s.close()
server.py
import socket
from random import randint,random
host = ''
port = 5560
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created.")
try:
s.bind((socket.gethostname(), 5560))
## s.bind((host, port))
except socket.error as msg:
print(msg)
print("Socket bind comlete.")
return s
def setupConnection():
s.listen(1)
conn, address = s.accept()
print("Connected to: " + address[0] + ":" + str(address[1]))
return conn
def getDustData():
data = 'some data'
return str(data)
def GET():
data = getDustData()
reply = 'MSG'+' '+data
return reply
def dataTransfer(conn):
while True:
data = conn.recv(1024)
data = data.decode('utf-8')
dataMessage = data.split(' ', 1)
command = dataMessage[0]
print(command)
if command == 'GET':
reply = GET()
else:
reply = 'Unknown Command'
conn.sendall(str.encode(reply))
conn.close()
if __name__=='__main__':
s = setupServer()
while True:
try:
conn = setupConnection()
dataTransfer(conn)
except:
pass
so how to make server keep sending data if command=='RUN' and my client keep listen to server
I want to make raspberry to keep sending data in every second via socket if my pc send command "RUN". and stop if my pc send command "STOP".
You can set a timeout on the socket.recv() operation and upon the timeout act as if a GET command were received. For this purpose change
data = conn.recv(1024)
to
try:
data = conn.recv(1024)
except socket.timeout:
data = b'GET' # simulate GET command on timeout
and add the handling of the RUN and STOP commands:
reply = ''
if command == 'GET':
reply = GET()
elif command == 'RUN':
conn.settimeout(1) # activate timeout for recv()
elif command == 'STOP':
conn.settimeout(None) # deactivate timeout for recv()
I'm trying to send a large file (.avi) over socket by sending the content of the file in chunks (a little bit like torrents). The problem is that the script doesn't send the file. I'm out of ideas here.
Any help or twerking of the script would be very appreciated.
Server:
import socket
HOST = ""
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
conn, addr = sock.accept()
print("Connected by ", str(addr))
while 1:
data = conn.recv(1024)
if data.decode("utf-8") == 'GET':
with open(downFile,'rb') as output:
l = output.read(1024)
while (l):
conn.send(l)
l = output.read(1024)
output.close()
conn.close()
Client:
import socket
HOST = "localhost"
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST,PORT))
while 1:
message = input()
sock.send(bytes(message,'UTF-8'))
conn.send(str.encode('GET'))
with open(downFile, 'wb+') as output:
while True:
rec = str(sock.recv(1024), "utf-8")
if not rec:
break
output.write(rec)
output.close()
print('Success!')
sock.close()
Here are a working client and server that should demonstrate transferring a file over a socket. I made some assumptions about what your code was supposed to do, for example, I assumed that the initial message the client sent to the server was supposed to be the name of the file to download.
The code also includes some additional functionality for the server to return an error message to the client. Before running the code, make sure the directory specified by DOWNLOAD_DIR exists.
Client:
import socket
import sys
import os
HOST = "localhost"
PORT = 8050
BUF_SIZE = 4096
DOWNLOAD_DIR = "downloads"
def download_file(s, down_file):
s.send(str.encode("GET\n" + down_file))
rec = s.recv(BUF_SIZE)
if not rec:
return "server closed connection"
if rec[:2].decode("utf-8") != 'OK':
return "server error: " + rec.decode("utf-8")
rec = rec[:2]
if DOWNLOAD_DIR:
down_file = os.path.join(DOWNLOAD_DIR, down_file)
with open(down_file, 'wb') as output:
if rec:
output.write(rec)
while True:
rec = s.recv(BUF_SIZE)
if not rec:
break
output.write(rec)
print('Success!')
return None
if DOWNLOAD_DIR and not os.path.isdir(DOWNLOAD_DIR):
print('no such directory "%s"' % (DOWNLOAD_DIR,), file=sys.stderr)
sys.exit(1)
while 1:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except Exception as e:
print("cannot connect to server:", e, file=sys.stderr)
break
file_name = input("\nFile to get: ")
if not file_name:
sock.close()
break
err = download_file(sock, file_name)
if err:
print(err, file=sys.stderr)
sock.close()
Server:
import socket
import sys
import os
HOST = ""
PORT = 8050
BUF_SIZE = 4096
def recv_dl_file(conn):
data = conn.recv(1024)
if not data:
print("Client finished")
return None, None
# Get command and filename
try:
cmd, down_file = data.decode("utf-8").split("\n")
except:
return None, "cannot parse client request"
if cmd != 'GET':
return None, "unknown command: " + cmd
print(cmd, down_file)
if not os.path.isfile(down_file):
return None, 'no such file "%s"'%(down_file,)
return down_file, None
def send_file(conn):
down_file, err = recv_dl_file(conn)
if err:
print(err, file=sys.stderr)
conn.send(bytes(err, 'utf-8'))
return True
if not down_file:
return False # client all done
# Tell client it is OK to receive file
sent = conn.send(bytes('OK', 'utf-8'))
total_sent = 0
with open(down_file,'rb') as output:
while True:
data = output.read(BUF_SIZE)
if not data:
break
conn.sendall(data)
total_sent += len(data)
print("finished sending", total_sent, "bytes")
return True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
keep_going = 1
while keep_going:
conn, addr = sock.accept()
print("Connected by", str(addr))
keep_going = send_file(conn)
conn.close() # close clien connection
print()
sock.close() # close listener
attempting message encryption with a basic client to host connection
client code:
import socket
import datetime
import time
import threading
tLock = threading.Lock()
shutdown = False
def receving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = socket.recvfrom(1024)
print (str(data))
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1',5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()
alias = input("Name: ")
IP=int(socket.gethostbyname(socket.gethostname()).replace(".","5"))
time=(int(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
qw=(int(str((time)+(IP))))
a=int("934")
b=int("346")
c=int("926")
d=int("9522")
e=int("7334")
f=int("5856")
g=int("2432")
h=int("2027")
i=int("7024")
j=int("828")
k=int("798")
m=int("593")
n=int("662")
l=int("5950")
o=int("357")
p=int("506")
q=int("237")
r=int("98")
s=int("372")
t=int("636")
u=int("553")
v=int("255")
w=int("298")
x=int("8822")
y=int("458")
z=int("657")
space=("633")
msg=input("")
msg=msg.replace("a",(str(a)))
msg=msg.replace("b",(str(b)))
msg=msg.replace("c",(str(c)))
msg=msg.replace("d",(str(d)))
msg=msg.replace("e",(str(e)))
msg=msg.replace("f",(str(f)))
msg=msg.replace("g",(str(g)))
msg=msg.replace("h",(str(h)))
msg=msg.replace("i",(str(i)))
msg=msg.replace("j",(str(j)))
msg=msg.replace("k",(str(k)))
msg=msg.replace("m",(str(m)))
msg=msg.replace("n",(str(n)))
msg=msg.replace("l",(str(l)))
msg=msg.replace("o",(str(o)))
msg=msg.replace("p",(str(p)))
msg=msg.replace("q",(str(q)))
msg=msg.replace("r",(str(r)))
msg=msg.replace("s",(str(s)))
msg=msg.replace("t",(str(t)))
msg=msg.replace("u",(str(u)))
msg=msg.replace("v",(str(v)))
msg=msg.replace("w",(str(w)))
msg=msg.replace("x",(str(x)))
msg=msg.replace("y",(str(y)))
msg=msg.replace("z",(str(z)))
msg=msg.replace(" ",(str(space)))
print(msg)
msg=int(msg)
msg=int(msg)*(qw)
print(msg)
fileb=open("key.txt","w")
filec=fileb.write(str(qw))
fileb.close()
file=open("msg decrypt.txt","w")
filea=file.write(str(msg))
file.close()
msg=(str(e)(msg))
print(IP)
print(qw)
if msg != 'q':
if msg != '':
s.sendto(alias.encode() + ": ".encode() + (str(msg).encode)(), server)
tLock.acquire()
msg = input(alias + "-> ")
tLock.release()
shudown = True
rT.join()
s.close()
host code:
import socket
import time
host = '127.0.0.1'
port = 5000
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
quitting = False
print ("Server Started.")
while not quitting:
try:
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print (time.ctime(time.time()) + str(addr) + ": :" + str(data))
for client in clients:
s.sendto(data, client)
except:
pass
s.close()
Im struggling as my poor excuse of a encryption is mostly numbers so therefore when im sending using the sendto function only uses str`s or so I think?
either way I get the error:
Traceback (most recent call last):
File "H:\client 2.py", line 103, in <module>
msg=(str(e)(msg))
TypeError: 'str' object is not callable
If msg is an index you should write :
msg = str(e)[msg]
Server
import socket
import sys
HOST = ''
PORT = 9000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
conn, addr = s.accept()
print 'Connecting from: ' + addr[0] + ':' + str(addr[1])
while 1:
message=raw_input(">")
s.sendto(message, (addr[0], addr[1]))
print(s.recv(1024))
How do I make this send a message to the client?
I can make it reply to a string the client sends to the server, but in this case I want the server to send the first message...
Can anyone help me, The solutions on google don't seem to work properly and I'm not sure what I'm doing wrong.
Since this is the 1st Google Stack Overflow result for this, I'll post a complete, working example for both a client and a server. You can start either 1st. Verified working on Ubuntu 18.04 w/ Python 3.6.9
text_send_server.py:
# text_send_server.py
import socket
import select
import time
HOST = 'localhost'
PORT = 65439
ACK_TEXT = 'text_received'
def main():
# instantiate a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket instantiated')
# bind the socket
sock.bind((HOST, PORT))
print('socket binded')
# start the socket listening
sock.listen()
print('socket now listening')
# accept the socket response from the client, and get the connection object
conn, addr = sock.accept() # Note: execution waits here until the client calls sock.connect()
print('socket accepted, got connection object')
myCounter = 0
while True:
message = 'message ' + str(myCounter)
print('sending: ' + message)
sendTextViaSocket(message, conn)
myCounter += 1
time.sleep(1)
# end while
# end function
def sendTextViaSocket(message, sock):
# encode the text message
encodedMessage = bytes(message, 'utf-8')
# send the data via the socket to the server
sock.sendall(encodedMessage)
# receive acknowledgment from the server
encodedAckText = sock.recv(1024)
ackText = encodedAckText.decode('utf-8')
# log if acknowledgment was successful
if ackText == ACK_TEXT:
print('server acknowledged reception of text')
else:
print('error: server has sent back ' + ackText)
# end if
# end function
if __name__ == '__main__':
main()
text_receive_client.py
# text_receive_client.py
import socket
import select
import time
HOST = 'localhost'
PORT = 65439
ACK_TEXT = 'text_received'
def main():
# instantiate a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket instantiated')
# connect the socket
connectionSuccessful = False
while not connectionSuccessful:
try:
sock.connect((HOST, PORT)) # Note: if execution gets here before the server starts up, this line will cause an error, hence the try-except
print('socket connected')
connectionSuccessful = True
except:
pass
# end try
# end while
socks = [sock]
while True:
readySocks, _, _ = select.select(socks, [], [], 5)
for sock in readySocks:
message = receiveTextViaSocket(sock)
print('received: ' + str(message))
# end for
# end while
# end function
def receiveTextViaSocket(sock):
# get the text via the scoket
encodedMessage = sock.recv(1024)
# if we didn't get anything, log an error and bail
if not encodedMessage:
print('error: encodedMessage was received as None')
return None
# end if
# decode the received text message
message = encodedMessage.decode('utf-8')
# now time to send the acknowledgement
# encode the acknowledgement text
encodedAckText = bytes(ACK_TEXT, 'utf-8')
# send the encoded acknowledgement text
sock.sendall(encodedAckText)
return message
# end function
if __name__ == '__main__':
main()
Use the returned socket object from 'accept' for sending and receiving data from a connected client:
while 1:
message=raw_input(">")
conn.send(message)
print conn.recv(1024)
You just have to use send
Server.py
import socket
s = socket.socket()
port = 65432
s.bind(('0.0.0.0', port))
s.listen(5)
while True:
c, addr = s.accept()
msg = b"Hello World!"
c.send(msg)
Client.py
import socket
s = socket.socket()
port = 65432
s.connect(('127.0.0.1', port))