I have encountered an error, i'm trying to render a character using coordinates of the character and then using the code reparentTo(render), however i get the following error: "TypeError: must be string or buffer, not None".
Traceback:
File "C:\On
line.py", line 1857, in <module>
run()
File "C:\Panda3D-1.8.1\direct\showbase\ShowBase.py", line 2921, in run
self.taskMgr.run()
File "C:\Panda3D-1.8.1\direct\task\Task.py", line 502, in run
self.step()
File "C:\Panda3D-1.8.1\direct\task\Task.py", line 460, in step
self.mgr.poll()
File "C:\On
line.py", line 1591, in updaterender
s.send(x)
TypeError: must be string or buffer, not None
Part of the Client code:
import direct.directbase.DirectStart
import pickle
from direct.gui.OnscreenText import OnscreenText
from direct.gui.DirectGui import *
from panda3d.core import *
from pandac.PandaModules import CardMaker
from pandac.PandaModules import NodePath
import socket
import sys
import select
print("Connecting...")
name = "fatie"
print 'Please enter the name you wish to use for your pirate?'
name = raw_input()
host = 'localhost'
port = 8303
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()
#When the connection is established the game loads.
#So if the code "Connected" comes up, the connection has been established.
print("Connected")
print("Loading Game")
#Game Loads Info connection to files then half way down the code
def updatecoords(task):
s.send(name)
print 'Name sent...'
def updatepos(task):
y = format(Cat.getPos())
s.send(y)
def updaterender(task):
x = Cat.reparentTo(render)
s.send(x)
return Task.cont
print 'Position sent'
def readServer(task):
try:
data = s.recv(4096)
print data
return Task.cont
except:
print 'no data received'
#Then further down
base.taskMgr.add(handleMovement, 'controlManager')
base.taskMgr.add(updatecoords, 'network coords')
base.taskMgr.add(updaterender, 'network coords')
base.taskMgr.add(updatepos, 'network coords')
base.taskMgr.add(readServer, 'read in')
Server Code:
import socket
import time
import pickle
import select
def broadcast(sock, message):
for socket in CONNECTION:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION.remove(socket)
HOST = ""
PORT = 8303
CONNECTION = []
RECV_BUFFER = 4096
maxclients = 5
print "Online Server started on port " + str(PORT)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('',PORT))
server_socket.listen(maxclients)
CONNECTION.append(server_socket)
while 1:
read_socks,wri_socks,err_socks = select.select(CONNECTION,[],[])
for sock in read_socks:
#New connection
if sock == server_socket:
socknew, addr = server_socket.accept()
CONNECTION.append(socknew)
print "Client (%s, %s) connected" % addr
broadcast(socknew, "[%s:%s] entered game\n" % addr)
else:
try:
data = socknew.recv(RECV_BUFFER)
if data:
print data
# broadcast_data(sock,data)
# print 'data was broadcast to'
# print CONNECTION_LIST.len()
except:
broadcast(sock, "Client (%s, %s) is offline" % addr)
sock.close()
CONNECTION.remove(sock)
continue
server_socket.close()
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.
I'm trying to create an online code to a game I'm making. Obviously, running this code gives an error. The error is [WinError 10053] An established connection was aborted by the software in your host machine.
Here's my code:
SERVER
from _thread import *
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
server = 'localhost'
port = 5555
server_ip = socket.gethostbyname(server)
try:
s.bind((server, port))
except socket.error as e:
print(str(e))
s.listen(2)
print("Currently waiting for other users...")
currentId = "0"
pos = ["0:50,50", "1:100,100"]
def threaded_client(conn):
global currentId, pos
conn.send(str.encode(currentId))
currentId = "1"
reply = ''
while True:
try:
data = conn.recv(2048)
reply = data.decode('utf-8')
if not data:
conn.send(str.encode("Goodbye"))
break
else:
print("Recieved: " + reply)
arr = reply.split(":")
id = int(arr[0])
pos[id] = reply
if id == 0: nid = 1
if id == 1: nid = 0
reply = pos[nid][:]
print("Sending: " + reply)
conn.sendall(str.encode(reply))
except:
break
print("Connection Closed")
conn.close()
while True:
conn, addr = s.accept()
start_new_thread(threaded_client, (conn,))
CLIENT
import time
class Network:
def __init__(self):
randomvar = "."
while True:
try:
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = "localhost" # For this to work on your machine this must be equal to the ipv4 address of the machine running the server
# You can find this address by typing ipconfig in CMD and copying the ipv4 address. Again this must be the servers
# ipv4 address. This feild will be the same for all your clients.
self.port = 5555
self.addr = (self.host, self.port)
self.id = self.connect()
break
except ConnectionRefusedError:
if randomvar != "Waiting for server...":
print("Waiting for server...")
randomvar = "Waiting for server..."
def getNumber(self):
pass
def connect(self):
self.client.connect(self.addr)
return self.client.recv(2048).decode()
def send(self, data):
"""
:param data: str
:return: str
"""
try:
self.client.send(str.encode(data))
reply = self.client.recv(2048).decode()
return reply
except socket.error as e:
return str(e)
n = Network()
print(n.send("Host"))
print(n.send("hello"))
On the server, the only things it receives Host, but not hello. That's where I get the error, but It won't tell me which line it is.
Any help?
You are ignoring the exception. Instead, print it out to get an idea of what is wrong:
Traceback (most recent call last):
File "D:\temp\python\server.py", line 39, in threaded_client
id = int(arr[0])
ValueError: invalid literal for int() with base 10: 'Host'
This leads to this line:
id = int(arr[0])
It looks like the server is expecting the messages to be in the form of id:msg but the client is not sending that. It is just sending the message without an id. You can check this in the server.
arr = reply.split(":")
if len(arr) != 2 or !arr[0].isdigit():
# Handle error....
When closing the connection, you are likely forgetting to close both sides.
I was able to modify your code to fit the scenario from this post which explains the root cause of [WinError 10053] An established connection was aborted by the software in your host machine, which lies in the WSAECONNABORTED error from WinSock, the windows sockets api
I made a more detailed answer about this on this SO post.
In this code, When I tried without applying multithreading on python socket, it works perfectly fine. But after using multithreading for concurrency, the first while loop works fine, but in the 2nd while loop, it takes it as 2nd thread, which doesn't complete the procedure of sending passkey to android. Here, I dont want 2nd loop as 2nd thread. How will I do that ? Any help will be appreciated!
import mysql.connector as mysql
import socket
import sys
import json
import threading
mydb1=mysql.connect(
user = 'rajat',
passwd = 'rajat',
host = 'localhost',
database = 'master_database'
)
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
self.addr = clientAddress
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", self.addr)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
#csocket, clientAddress = s.accept()
#print ('Connect with ' + addr[0] + ':' + str(addr[1]))
df7 = self.csocket.recv(1024)#Receiving the data in df7
df8 = json.loads(df7)
df2 = list(df8.values())
mycursor4=mydb1.cursor()
mycursor4.execute("SELECT bar_code_no FROM form_simpleform")
obj1 = mycursor4.fetchone()
qr_obj=print(obj1[0])
mycursor3 = mydb1.cursor()
mycursor3.execute("SELECT bar_code_no FROM bar_code")
obj2 = mycursor3.fetchone()
bar_obj=print(obj2[0])
if qr_obj == bar_obj:
print("This bar code has a existence in the database.")
else:
print("This bar code does not exist.")
mycursor1=mydb1.cursor()
mycursor1.execute("SELECT * FROM form_simpleform WHERE id=1")
df3=mycursor1.fetchone()
if df2 == (list(df3)):
print('Data of QR Code also Exists')
mycursor2 = mydb1.cursor()
mycursor2.execute("SELECT * FROM android_display_data")
df4 = mycursor2.fetchone()
self.csocket.send(str(df4).encode('utf-8'))
print("Data(Name, Email_id, Phone_No) is sent to the client ")
self.csocket.close()
message=[]
while True:
clientsock, clientAddress = s.accept()
message = self.csocket.recv(1024).decode('ISO-8859-1')
print("Received new message from client")
op=((message).split(","))
print(op)
d = dict(s.split(':') for s in op)
yo = print(list(d.values()))
mycursor5 = mydb1.cursor()
sql2 = ("INSERT INTO imeiserial (IMEI, SimSerialNumber) VALUES (%s, %s)")
result = mycursor5.execute(yo, sql2)
print("Data inserted into bar_code Database")
pass_key = '90i5n4r16191'
self.csocket.send(str(pass_key).encode('utf-8'))
print(" Passkey send to Android ")
break
else:
print('Invalid Data')
break
print('Connection Closed!!')
#s.close()
LOCALHOST = "192.168.0.121"
PORT = 8011
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
s.listen(5)
clientsock, clientAddress = s.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
The Output which I am getting-
Server started
Waiting for client request..
Connection from : ('192.168.0.108', 42762)
456456
456456
This bar code has a existence in the database.
Data of QR Code also Exists
Data(Name, Email_id, Phone_No) is sent to the client
Connection from : ('192.168.0.108', 42764)
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Pallavai\Nox_share\AnacondaNEW\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "server-side2.py", line 34, in run
df8 = json.loads(df7)
When you run ClientThread class you are trying to call for clientAdress variable that is never defined in your current scope.
def run(self):
print ("Connection from : ", clientAddress)
Henceforth clientAdress throws an error. To way to solve this is, assign clientAddress during init method then call it via self.clientAddress.
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
self.addr = clientAddress
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", self.addr)
I want to write a bridge adapt between non ZMQ socket and ZMQ socket.
client code:
import socket
if __name__ == '__main__':
HOST = "localhost"
PORT = 8888
BUFFER = 4096
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print sock
ret = sock.connect((HOST, PORT))
print ret
ret = sock.send('hello, tcpServer!')
print ret
recv = sock.recv(BUFFER)
print ('[tcpServer siad]: %s' % recv)
sock.close()
except e:
print e
proxy code, use this proxy to send request to ZMQ_REP server.
import zmq
if __name__ == '__main__':
context = zmq.Context()
socket = context.socket(zmq.STREAM)
socket.bind("tcp://*:8888")
socket_req = context.socket(zmq.REQ)
socket_req.connect("tcp://localhost:5556")
while True:
clientid, message = socket.recv_multipart();
print("id: %r" % clientid)
print("request:",message.decode('utf8'))
socket_req.send(clientid, flags=zmq.SNDMORE, copy=False)
socket_req.send("Hi", copy=False)
clientid, message = socket_req.recv_multipart()
print("id: %r" % clientid)
print("request:",message.decode('utf8'))
ZMQ_REP server code:
import zmq
import time
import sys
if __name__ == '__main__':
port = '5556'
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:%s" % port)
while True:
message = socket.recv()
print "Received request: ", message
time.sleep(1)
socket.send("world from %s" % port)
the REQ get error:
Received request: k
Traceback (most recent call last):
File "req_server.py", line 21, in <module>
socket.send("world from %s" % port)
File "zmq/backend/cython/socket.pyx", line 574, in zmq.backend.cython.socket.Socket.send (zmq/backend/cython/socket.c:5434)
File "zmq/backend/cython/socket.pyx", line 621, in zmq.backend.cython.socket.Socket.send (zmq/backend/cython/socket.c:5196)
File "zmq/backend/cython/socket.pyx", line 181, in zmq.backend.cython.socket._send_copy (zmq/backend/cython/socket.c:2035)
File "zmq/backend/cython/checkrc.pxd", line 21, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:6248)
zmq.error.ZMQError: Operation cannot be accomplished in current state
First point: It's generally not recommended to use REQ/REP in zmq. Use the more general DEALER/ROUTER combination. The only difference:
When the ROUTER recvs, a routing ID is the first part of the message. This is used to route replies back to the sender.
the lock-step req/rep/req/rep sequence is not enforced (this is the error you are seeing).
Here's a version of your proxy using DEALER:
import zmq
if __name__ == '__main__':
context = zmq.Context()
socket = context.socket(zmq.STREAM)
socket.bind("tcp://*:8888")
socket_req = context.socket(zmq.DEALER)
socket_req.connect("tcp://localhost:5556")
while True:
clientid, message = socket.recv_multipart()
print("id: %r" % clientid)
print("request: %s" % message.decode('utf8'))
socket_req.send(message)
reply = socket_req.recv()
print("reply: %s" % reply.decode('utf8'))
socket.send_multipart([clientid, reply])
And your server, using ROUTER:
import zmq
import time
import sys
if __name__ == '__main__':
port = 5556
if len(sys.argv) > 1:
port = int(sys.argv[1])
context = zmq.Context()
socket = context.socket(zmq.ROUTER)
socket.bind("tcp://127.0.0.1:%i" % port)
while True:
message = socket.recv_multipart()
req_id = message[0]
print("Received request: %s" % message[1:])
time.sleep(1)
socket.send_multipart([req_id, "world from %s" % port])
socket_req.send(clientid, flags=zmq.SNDMORE, copy=False)
socket_req.send("Hi", copy=False)
Best guess is that it's not properly registering the SNDMORE flag and attempting to send a whole new request rather than appending to the first one (thus breaking the strict SEND/RECEIVE order for REQ sockets)... thus the "current state" of the socket would not allow it to send the second part of your message. Try using send_multipart(), or validating that your parameters are being passed in correctly.
This is the code that I have used.But I don't get actual result that I want.When I execute code ChatServer file works properly,but ChatClient gives only one line(Usage : python telnet.py hostname port).Please Help me.I am new in python.
The server code:
#!/usr/bin/env python
#!/usr/bin/env python
"""
A basic, multiclient 'chat server' using Python's select module
with interrupt handling.
Entering any line of input at the terminal will exit the server.
"""
import select
import socket
import sys
import signal
from communication import send, receive
BUFSIZ = 1024
class ChatServer(object):
""" Simple chat server using select """
def __init__(self, port=3490, backlog=5):
self.clients = 0
# Client map
self.clientmap = {}
# Output socket list
self.outputs = []
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind(('',port))
print 'Listening to port',port,'...'
self.server.listen(backlog)
# Trap keyboard interrupts
signal.signal(signal.SIGINT, self.sighandler)
def sighandler(self, signum, frame):
# Close the server
print 'Shutting down server...'
# Close existing client sockets
for o in self.outputs:
o.close()
self.server.close()
def getname(self, client):
# Return the printable name of the
# client, given its socket...
info = self.clientmap[client]
host, name = info[0][0], info[1]
return '#'.join((name, host))
def serve(self):
inputs = [self.server,sys.stdin]
self.outputs = []
running = 1
while running:
try:
inputready,outputready,exceptready = select.select(inputs, self.outputs, [])
except select.error, e:
break
except socket.error, e:
break
for s in inputready:
if s == self.server:
# handle the server socket
client, address = self.server.accept()
print 'chatserver: got connection %d from %s' % (client.fileno(), address)
# Read the login name
cname = receive(client).split('NAME: ')[1]
# Compute client name and send back
self.clients += 1
send(client, 'CLIENT: ' + str(address[0]))
inputs.append(client)
self.clientmap[client] = (address, cname)
# Send joining information to other clients
msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client))
for o in self.outputs:
# o.send(msg)
send(o, msg)
self.outputs.append(client)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = 0
else:
# handle all other sockets
try:
# data = s.recv(BUFSIZ)
data = receive(s)
if data:
# Send as new client's message...
msg = '\n#[' + self.getname(s) + ']>> ' + data
# Send data to all except ourselves
for o in self.outputs:
if o != s:
# o.send(msg)
send(o, msg)
else:
print 'chatserver: %d hung up' % s.fileno()
self.clients -= 1
s.close()
inputs.remove(s)
self.outputs.remove(s)
# Send client leaving information to others
msg = '\n(Hung up: Client from %s)' % self.getname(s)
for o in self.outputs:
# o.send(msg)
send(o, msg)
except socket.error, e:
# Remove
inputs.remove(s)
self.outputs.remove(s)
self.server.close()
if __name__ == "__main__":
ChatServer().serve()
The chat client:
#! /usr/bin/env python
"""
Simple chat client for the chat server. Defines
a simple protocol to be used with chatserver.
"""
import socket
import sys
import select
from communication import send, receive
BUFSIZ = 1024
class ChatClient(object):
""" A simple command line chat client using select """
def __init__(self, name, host='127.0.0.1', port=3490):
self.name = name
# Quit flag
self.flag = False
self.port = int(port)
self.host = host
# Initial prompt
self.prompt='[' + '#'.join((name, socket.gethostname().split('.')[0])) + ']> '
# Connect to server at port
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, self.port))
print 'Connected to chat server#%d' % self.port
# Send my name...
send(self.sock,'NAME: ' + self.name)
data = receive(self.sock)
# Contains client address, set it
addr = data.split('CLIENT: ')[1]
self.prompt = '[' + '#'.join((self.name, addr)) + ']> '
except socket.error, e:
print 'Could not connect to chat server #%d' % self.port
sys.exit(1)
def cmdloop(self):
while not self.flag:
try:
sys.stdout.write(self.prompt)
sys.stdout.flush()
# Wait for input from stdin & socket
inputready, outputready,exceptrdy = select.select([0, self.sock], [],[])
for i in inputready:
if i == 0:
data = sys.stdin.readline().strip()
if data: send(self.sock, data)
elif i == self.sock:
data = receive(self.sock)
if not data:
print 'Shutting down.'
self.flag = True
break
else:
sys.stdout.write(data + '\n')
sys.stdout.flush()
except KeyboardInterrupt:
print 'Interrupted.'
self.sock.close()
break
if __name__ == "__main__":
import sys
if len(sys.argv)<3:
sys.exit('Usage: %s chatid host portno' % sys.argv[0])
client = ChatClient(sys.argv[1],sys.argv[2], int(sys.argv[3]))
client.cmdloop()
###############################################################################
# The communication module (communication.py)
###############################################################################
import cPickle
import socket
import struct
marshall = cPickle.dumps
unmarshall = cPickle.loads
def send(channel, *args):
buf = marshall(args)
value = socket.htonl(len(buf))
size = struct.pack("L",value)
channel.send(size)
channel.send(buf)
def receive(channel):
size = struct.calcsize("L")
size = channel.recv(size)
try:
size = socket.ntohl(struct.unpack("L", size)[0])
except struct.error, e:
return ''
buf = ""
while len(buf) < size:
buf = channel.recv(size - len(buf))
return unmarshall(buf)[0]