when i running my chat program,an attribute error is there all the time.
could someone please explain why this error occur in my code and suggest solutions.
the chat program is
import socket
import select
import sys
#list for socket descriptors
socket_list = []
host = socket.gethostname()
port = 5009
def chat_server():
server_socket = socket.socket(socket.AF_INIT, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((host, port))
server_socket.listen(10)
# add server socket to the list
socket_list.append(server_socket)
print "chat server started on port" + str(port)
while 1:
#get the list of sockets to be read through select
read, write, error = select.select(socket_list, [], [])
for sock in read:
if sock == server_socket:
sock_obj, addr = server_socket.accept()
socket_list.append(sock_obj)
print "Client (%s, %s) connected"%addr)
broadcast(srver_socket, sock_obj,
"[%s, %s] entered our chat address" %addr)
else :
#process data recieved from client,
data = sock.recv(4000)
if data :
broadcast(server_socket0, sock,
'Message[' + addr[0] + ':'
+ str(addr[1]) + '] -' + data.strip())
else :
# remove the broken socket
if sock in socket_list :
socket_list.remove(sock)
broadcast(server_socket, sock,
"Client (%s, %s) is offline" %addr)
server_socket.close()
# broadcast the messages to our clients
def broadcast (server_socket, sock, msg):
for sockets in socket_list :
if sockets != server_socket and sockets != sock :
socket.send(msg)
when i run this code the following errors occur,
please give some suggestion to make it correct
Traceback (most recent call last):
File "chat_server.py", line 55, in <module>
chat_server()
File "chat_server.py", line 11, in chat_server
server_socket = socket.socket(socket.AF_INIT, socket.SOCK_DGRAM)
AttributeError: 'module' object has no attribute 'AF_INIT'
Which version you are using, did not find socket.AF_INIT
socket.AF_INET exist in python 2.7 version (https://docs.python.org/2/library/socket.html)
Related
Here's the code, I wonder how to save the messages separately.
It can only get and send messages back to client. But I can't distinguish which are from client 1 and which are from client 2. Is there any way to save these messages into separate list or something else? so that I can distinguish them
Client 1:
import socket
import sys
messages = [b'This is client 1',
b'It is a good day!',
]
server_address = ('localhost', 1234)
socks = [ socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
for i in range(1)]
print('connecting to %s port %s' % server_address)
for s in socks:
s.connect(server_address)
for message in messages:
for s in socks:
s.send(message)
for s in socks:
data = s.recv(1024)
print(data.decode())
if not data:
print(sys.stderr, 'closing socket', s.getsockname())
Client 2:
import socket
import sys
messages = [b'This is client 2',
b'It is raining today',
]
server_address = ('localhost', 5678)
socks = [ socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
for i in range(1)]
print('connecting to %s port %s' % server_address)
for s in socks:
s.connect(server_address)
for message in messages:
for s in socks:
s.send(message)
for s in socks:
data = s.recv(1024)
print(data.decode())
if not data:
print(sys.stderr, 'closing socket', s.getsockname())
Server:
import selectors
import socket
sel = selectors.DefaultSelector()
def accept(sock, mask):
conn, addr = sock.accept()
print('accepted', conn, 'from', addr)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read)
def read(conn, mask):
data = conn.recv(1000)
if data:
conn.send(data)
else:
print('closing', conn)
sel.unregister(conn)
conn.close()
sock = socket.socket()
sock.bind(('localhost', int(input())))
sock.listen(1)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)
while True:
events = sel.select()
for key, mask in events:
callback = key.data
callback(key.fileobj, mask)
If you want to validate the ip on the network layer then you can use the variable addr that you create when you accept the connection.
However when you are doing this with multiple clients on the same host then it will not work since the ip is the same.
This will also not work if you are behind a NAT, because you would just get the IP of the nearest router in your network.
Another solution would be to validate the client on the application layer and simply give the client an identification value that you pass into the message that you send from the client.
I have a listener on a tcp localhost:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def client_socket():
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
while 1:
print 'Listening for client...'
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
print "Received all the data"
i=0
for x in param:
print x
#break
elif data:
print "received data: ", data
param.insert(i,data)
i+=1
#print "End of transmission"
s.close()
I am trying to send a JSON object to the same port on the local host:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender' : local_ip,
'instruction' : direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data)
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data)
data = s.recv(1024)
print('Received', repr(data))
However, I get a socket error:
socket.error: [Errno 98] Address already in use
What am I doing wrong? Will this work or do I need to serialize the JSON object?
There are a few problems with your code, but the one that will likely address your issue is setting the SO_REUSEADDR socket option with:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
after you create the socket (with socket.socket(...) but before you attempt to bind to an address (with s.bind().
In terms of other things, the two "halves" of the code are pretty inconsistent -- like you copied and pasted code from two different places and tried to use them?
(One uses a context manager and Python 3 print syntax while the other uses Python 2 print syntax...)
But I've written enough socket programs that I can decipher pretty much anything, so here's a working version of your code (with some pretty suboptimal parameters e.g. a buffer size of 1, but how else would you expect to catch a single ;?)
Server:
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
BUFFER_SIZE = 1
def server_socket():
data = []
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen()
while 1: # Accept connections from multiple clients
print('Listening for client...')
conn, addr = s.accept()
print('Connection address:', addr)
while 1: # Accept multiple messages from each client
buffer = conn.recv(BUFFER_SIZE)
buffer = buffer.decode()
if buffer == ";":
conn.close()
print("Received all the data")
for x in data:
print(x)
break
elif buffer:
print("received data: ", buffer)
data.append(buffer)
else:
break
server_socket()
Client:
import socket
import json
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender': local_ip,
'instruction': direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data + ";")
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data.encode())
data = s.recv(1024)
print('Received', repr(data))
json_message("SOME_DIRECTION")
this is my server:
import socket
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
while True:
(client_name, client_adress) = server_socket.recvfrom(1024)
print chr(port)
server_socket.close()
this is my client:
import socket
message = raw_input("Enter a message: ")
for letter in message:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
my_socket.sendto("", ('127.0.0.1', ord(letter)))
(data, remote_adress) = my_socket.recvfrom(1024)
my_socket.close()
print 'The server sent: ' + data
I'm not very good in python, but I think you should save your sockets to list inside for and then use select function in infinite loop outside for
import socket
import select
sockets = []
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
sockets.append(server_socket)
empty = []
while True:
readable, writable, exceptional = select.select(sockets, empty, empty)
for s in readable:
(client_data, client_address) = s.recvfrom(1024)
print client_address, client_data
for s in sockets:
s.close()
I am learning how to create multithreaded socket server in Python. I used example from some site that I don't remember. I am trying to create simple plugin system but I am not successful. It says that I am passing 3 arguments instead of 2. This is my code:
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
data_sanitized = data.rstrip()
print repr(addr) + ' received: ' + repr(data_sanitized)
from plugins.helloWorld import helloWorld
clazz.fireIt(clientsock,data)#HERE IS THE PROBLEM I THINK
if "close" == data.rstrip(): break
clientsock.close()
print addr, "CLIENT CLOSED CONNECTION"
if __name__=='__main__':
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(ADDR)
print 'STARTED SERVER, WAITING FOR CONNECTIONS', PORT
serversock.listen(5)
while 1:
clientsock, addr = serversock.accept()
print 'INCOMING CONNECTION FROM: ', addr
thread.start_new_thread(handler, (clientsock, adde))
and this is my plugin:
from socket import *
def response(key):
return '<response>' + key + '</response>'
class helloWorld():
def fireIt(clientsock,data):
print clientsock
clientsock.send(response(data))
print 'SENDING: ' + repr(response(data))
Thank you
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()