Client:
#The program should send two strings and the server should return the interclassed string back
import socket
import time
import sys
HEADERSIZE=10
firstString = input("First string: ")
secondString = input("Second string: ")
host = "127.0.0.1"
port = 8888
firstString = f'{len(firstString):<{HEADERSIZE}}'+firstString
secondString = f'{len(secondString):<{HEADERSIZE}}'+secondString
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(bytes(firstString, 'utf-8'))
s.send(bytes(secondString, 'utf-8'))
fullMsg=''
while 1:
msg = s.recv(8)
if len(msg)<=0:
break
fullMsg += msg.decode('utf-8')
print(fullMsg)
s.close()
Server:
#trebuie trimisa si dimensiunea
import socket
def interclass(firstString , secondString):
i =0
j =0
interString=''
while i < len(firstString) and j < len(secondString):
if firstString[i] < secondString[j]:
interString+=firstString[i]
i=i+1
else:
interString+=secondString[j]
j=j+1
while i < len(firstString):
interString += firstString[i]
i=i+1
while j < len(secondString):
interString+=secondString[j]
j=j+1
return interString
host = "127.0.0.1"
port = 8888;
HEADERSIZE=10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
conn, addr = s.accept()
messages=[]
newMsg = True
fullMsg = ''
msgLength = -1
while True:
msg = conn.recv(16)
if len(msg)<=0:
break
msg = msg.decode('utf-8')
fullMsg += msg
if len(fullMsg)>=HEADERSIZE and newMsg == True:
newMsg = False
msgLength = int(fullMsg[:HEADERSIZE-1])
fullMsg = fullMsg[HEADERSIZE:HEADERSIZE+1+msgLength]
if not newMsg and len(fullMsg)>=msgLength:
messages.append(fullMsg[:msgLength])
fullMsg = fullMsg[msgLength:]
newMsg = True
interString = interclass(messages[0], messages[1])
conn.sendall(bytes(interString,'utf-8'))
conn.close()
The application works until I try the part where I try to send data from the server. It all blocks at the recv() command in the client. I searched all the internet for a solution and I tried making it a non-blocked socket and deal with exception... Still not working. I would appreciate some help. Thanks!!
Related
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
I am getting the above error..My server and client can send and receive their first messages but I get this error if I try to send more than one message.
My Server Code is here
import socket
import threading
import time
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5354
maxconnections = 9
ip = socket.gethostbyname(socket.gethostname())
print(ip)
server = (ip, port)
FORMAT = 'utf-8'
listensocket.bind((server))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
msg = f'\[ALERT\] {address} has joined the chat.'
lstbox.insert(0, msg)
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Client: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5986
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
And my client code is same with minor difference
import socket
import time
import threading
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5986
maxconnections = 9
ip = socket.gethostname()
print(ip)
FORMAT = 'utf-8'
host = 'MY_IP' # My actual ip is there in the code
listensocket.bind((host, port))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Server: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5354
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
Please let me know what changes are required to be made in order to make it run for every message.
I tried to put
g.connect((hostname, port))
the above line in the loop so that it will connect every time loop iterates. But it did not help.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
...
if at==0:
g.connect((hostname, port))
...
g.send(msg.encode())
at += 1
else:
...
g.send(msg.encode())
In the if at==0 condition it connects to the server, in the else part not. But is still trying to send something on the not connected socket.
Why does my Python P2P client works over LAN but not the Internet and how can I fix this!
I would like to make a p2p messenger and I just don't know why the p2p functionality with UDP Hole Punching is not working. Please help!
Server:
This server holds peers ips and ports for the client.
The ping function pings the peers to check if they are still alive.
'''
import threading
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("IP_ADDRESS", 8081))
addrs = []
print('Server started...')
def ping(addr):
try:
sock.sendto(b'ping', addr)
sock.settimeout(1)
data, addr = sock.recvfrom(1024)
sock.settimeout(None)
return True
except Exception as ex:
sock.settimeout(None)
return False
while True:
data, addr = sock.recvfrom(1024)
print(addr)
sock.sendto((addr[0]+' '+str(addr[1])).encode(), addr)
for a in addrs:
p = ping(a)
print(p, a)
if p:
sock.sendto((a[0]+' '+str(a[1])).encode(), addr)
addrs.append(addr)
sock.sendto(b'DONE', addr)
'''
Client:
import threading
import socket
import time
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.addrs = []
self.chat_logs = ''
self.peers = ''
self.self_data = ('0.0.0.0', 0)
def recv_thread(self):
while True:
try:
data, addr = self.sock.recvfrom(1024)
if data == b'ping':
self.sock.sendto(b'pong', addr)
else:
data = data.decode()
new_user = True
for a in self.addrs:
if a == addr:
new_user = False
if new_user == False:
self.chat_logs += addr[0]+':'+str(addr[1])+' - '+data+'\n'
else:
self.chat_logs += addr[0]+':'+str(addr[1])+' joined the p2p network... \n'
self.addrs.append(addr)
except Exception as ex:
print(ex)
def send_msg(self):
message = self.messageBox.text()
if len(message) > 0:
self.chat_logs += 'You - '+message+'\n'
self.chatBox.setPlainText(self.chat_logs)
for a in self.addrs:
try:
self.sock.sendto(message.encode(), a)
except:
self.addrs.remove(a)
def get_peers(self, host):
host = host.split(':')
host = (host[0], int(host[1]))
self.sock.sendto(b'PEERS', host)
self.self_data, addr = self.sock.recvfrom(512)
self.self_data = self.self_data.decode().split()
self.self_data = (self.self_data[0], int(self.self_data[1]))
while True:
data, addr = self.sock.recvfrom(512)
if data == b'DONE':
break
else:
data = data.decode().split()
self.addrs.append((data[0], int(data[1])))
print(self.addrs)
for a in self.addrs:
try:
self.sock.sendto(b'join', a)
except:
self.addrs.remove(a)
t = threading.Thread(target=self.recv_thread)
t.start()
def connect_to_pears_network(self):
dlg = CustomDialog()
if dlg.exec():
text = dlg.message.text()
if len(text) > 6:
self.get_peers(text)
else:
pass
I hope I did this post right this is my first time making a post.
this is the strangest error i ever had (i write this because most of my post is code!!
can you help me?
i have a new error :/
line 43: conn.send = command.encode()
NameError: name 'conn' is not defined here's the code:
import os
import socket
import sys
from _thread import *
mm = 0
owncmds = ["dir", "erase"]
def clientthread(conn):
buffer = ""
data = conn.recv(8192)
buffer += data
print(buffer)
# conn.sendall(reply)
def main():
try:
host = socket.gethostname()
port = 6666
tot_socket = input("Wie viele Clients sind zugelassen?: ")
list_sock = []
for i in range(int(tot_socket)):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port + i))
s.listen(2)
list_sock.append(s)
print("[*] Server listening on %s %d" % (host, (port + i)))
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print('[*] Connected with ' + addr[0] + ':' + str(addr[1]))
start_new_thread(clientthread, (conn,))
finally:
s.close()
main()
while mm < 1:
command = input(str("Command: "))
if command not in owncmds:
conn.send(command.encode())
else:
if command == "dir":
result = conn.recv(1024)
result = result.decode()
print(result)
if command == "erase":
command = command + "/F /Q "
FileErase = input(str("Filename: "))
command = command + FileErase
conn.send(command.encode())
print("Der Befehl wurde gesendet, warte auf Akzeptierung")
print("")
I'm making a basic chatroom and I want the received messages to show up when I'm also typing a message. I've looked it up, but from what I can tell it only works with a GUI, and I would prefer not to write a GUI.
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
str_return = ("")
str_send = ("blep")
old = ("blep")
port = input("Enter Port ")
try:
s.connect(("localhost", int(port)))
print("Connecting")
while True:
str_send = input("Enter message: ")
if str_send == ("exit"):
break
s.send(bytes(str_send, 'utf-8'))
str_recv = s.recv(1024)
print(str_recv.decode('utf-8'))
s.close()
except:
print("setting up server")
s.bind(('localhost', int(port)))
s.listen(5)
connect, addr = s.accept()
connect.sendto(bytes(str_return, 'utf-8'), addr)
print("Connection Address:" + str(addr))
while True:
str_send = input("Enter message: ")
if str_send == ("exit"):
break
connect.sendto(bytes(str_send, 'utf-8'), addr)
str_recv, temp = connect.recvfrom(1024)
print(str_recv.decode('utf-8'))
print("bye")
How can I make this work?
When doing the put command I am getting this error. I can't seem to figure out why.
line 41, in
data = client.recv(1024)
error: [Errno 10053] An established connection was aborted by the software in your host machine
Here is my client code:
import socket
import sys
import os
HOST = 'localhost'
PORT = 8082
size = 1024
def ls():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
result = s.recv(size)
print result
s.close()
return
def put(command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command)
string = command.split(' ', 1)
input_file = string[1]
with open(input_file, 'rb') as file_to_put:
for data in file_to_put:
s.sendall(data)
s.close()
return
def get(command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(command)
string = command.split(' ', 1)
input_file = string[1]
with open(input_file, 'wb') as file_to_get:
while True:
data = s.recv(1024)
print data
if not data:
break
file_to_get.write(data)
file_to_get.close()
s.close()
return
done = False
while not done:
userInput = raw_input()
if "quit" == userInput:
done = True
elif "ls" == userInput:
ls()
else:
string = userInput.split(' ', 1)
if (string[0] == 'put'):
put(userInput)
elif (string[0] == 'get'):
get(userInput)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.close()
print "Closing connection."
And server code:
import socket
import os
import sys
host = ''
port = 8082
backlog = 5
size = 1024
serverID = socket.gethostbyname(socket.gethostname())
info = 'SERVER ID: {} port: {}'.format(serverID, port)
print info
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
done = False
#Loop until client sends 'quit' to server
while not done:
client, address = s.accept()
data = client.recv(size)
print "Server received: ", data
if data:
client.send("Server Says... " + data)
if data == "quit":
done = True
elif data == "ls":
data = os.listdir('c:\\') # listing contents of c: drive
client.send(str(data))
print data
else:
string = data.split(' ', 1)
data_file = string[1]
if (string[0] == 'put'):
with open(data_file, 'wb') as file_to_write: # opening sent filename to write bytes
while True:
data = client.recv(1024)
if not data:
break
file_to_write.write(data) # writing data
file_to_write.close() # closing file
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open('C:\\' + data_file, 'rb') as file_to_send:
for data in file_to_send:
client.send(data)
print 'Send Successful'
client.close()
s.close()
print "Server exiting."