Python sockets for a n-players game - python

I'm a python(3) begginer and I want to do a n-players game. This players will connect to the server to play. I'm practicing with an easy example I've found, but when I run it, it throws an error "Traceback (most recent call last)" and another "OS [WinError 10048]", anyone knows why? Could you explain me how to try it out in my pc, being both client and server?.
import socket
#Server
s = socket.socket()
s.bind((socket.gethostname(), 9999))
s.listen(1)
sc, addr = s.accept()
while True:
received = sc.recv(1024)
if received == "quit":
break
print ("Received:", received)
sc.send(received)
print ("bye")
sc.close()
s.close()
#Client
s = socket.socket()
s.connect((socket.gethostname(), 9999))
while True:
message = input("> ")
s.send(message)
if message == "quit":
break
print ("bye")
s.close()
I've previously read that it can be a problem with the Firewall, but that's not my case.
Thank you for any help you can bring me!

save both files in the same directory and open 2 terminals there
run server.py first (it should just wait for a connection)
(if you already have server.py running somewhere this will result in an error, only one instance of server.py may be running on a given computer/port at a time )
then run client.py (while server.py is running in first terminal)
client.py
import socket
s = socket.socket()
s.connect((socket.gethostname(), 9999))
while True:
message = input("> ")
s.send(message)
if message == "quit":
break
print ("bye")
s.close()
server.py
import socket
#Server
s = socket.socket()
s.bind((socket.gethostname(), 9999))
s.listen(1)
sc, addr = s.accept()
while True:
received = sc.recv(1024)
if received == "quit":
break
print ("Received:", received)
sc.send(received)
print ("bye")
sc.close()
s.close()

i think your problem is in your adress binding. instead of s.bind((socket.gethostname(), 9999)), it should be s.bind((socket.gethostname(socket.gethostbyname()), 9999))

Related

Python socket wont stop spam

I am sending a message to client but the client wont stop spamming the message
server.py
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
hostname = socket.gethostname()
hostip = socket.gethostbyname(hostname)
port = 462
server.bind((hostname, port))
server.listen(1)
print((hostip, port))
client, address = server.accept()
print("New connection!: ", address)
while True:
data = input("Do something:")
if data == "help":
print("test: 'test'")
input("Click ENTER to continue")
elif data == "test":
client.send("test".encode('ascii'))
else:
continue
client.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 462
s.connect(('', port))
data = s.recv(1024)
while True:
if data.decode('ascii') == "test":
print(data.decode('ascii'))
else:
continue
You didn't post the full example, but I think I can see where the problem is.
Where/when do you actually read/receive the data from the socket in the client.py?
Because it looks like you received the data, saved it in the in the "data" variable and then you keep looping forever decoding this data, not reading from socket.
So I think you need to move your while loop in client.py outside, so that the read/receive from socket method is inside your loop, not outside as it appears it is now.
Edit: Yup, from the full code that you posted I can see that indeed, this should fix your problem.

Locking another computer using sockets without interrupting the connection

I am trying to set up a server that can send each client - commands.
One command is 'lock' which locks the screen of the client.
When a client gets the word "lock" it runs this code on the client:
import ctypes
ctypes.windll.user32.LockWorkStation()
This code does lock the screen however- it ends my connection with the client..
How can I make the client stay connected but still locked?
Note: The locking is not forever! it is only once, like putting the client's computer in sleep mode until he wants to unlock the screen.
Hope I was clear enough. Thanks for helping!
Server:
import socket
def main():
sock = socket.socket()
sock.bind(('0.0.0.0', 4582))
print("Waiting for connections...")
sock.listen(1)
conn, addr = sock.accept()
print ("New connection from: ", addr)
while 1:
command = input("Enter command> ")
if command == 'shutdown':
sock.send(b'shutdown')
elif command == 'lock':
sock.send(b'lock')
else:
print ("Unknown command")
data = sock.recv(1024)
print (data)
if __name__ == '__main__':
main()
Client:
import socket
import ctypes
def main():
sock = socket.socket()
sock.connect(('127.0.0.1', 4582))
while 1:
data = sock.recv(1024)
print (data)
if data == 'lock':
sock.send(b'locking')
ctypes.windll.user32.LockWorkStation()
sock.recv(1024)
if __name__ == '__main__':
main()
I adapted the example from the Python docs to your needs.
Example for server.py:
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
print('Waiting for connection...')
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = input('Which command? ')
if data in ['lock', 'shutdown']:
conn.send(data.encode())
else:
print('Command unknown')
Example for client.py:
import ctypes
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
s.connect((HOST, PORT))
while True:
data = s.recv(1024).decode()
if not data:
print('Server disconnected')
break
print('Received command:', data)
if data == 'shutdown':
print('Shutting down client...')
break
if data == 'lock':
print('Locking...')
ctypes.windll.user32.LockWorkStation()

TypeError: 'module' object is not callable. I tride socket.socket() and from socket import socket still not working

I have this code but it gives me this
from socket import socket
def main():
host= "127.0.0.1"
port = 5000
s= socket()
s.connect((host,port))
message = raw_input
while message != q:
s.send(message)
data = s.recv(1024)
print "recieved from server: "+str(data)
message = raw_input("->")
s.close()
if __name__ == '__main__':
main()
I am new to python, i am following a tutorial and this error does not happen in the tutorial I dont understand whats happening thans
As far as I can see, there are many errors in your script, this one should work:
import socket
def main():
host= "127.0.0.1"
port = 5000
s= socket.socket() #Instead of s = socket()
s.connect((host,port))
while True:
message = raw_input("->")
s.send(message)
data = s.recv(1024)
print "recieved from server: "+str(data)
if message == 'q':
break
s.close()
#This must be placed outside of the function
#you want to call (in this case, main())
if __name__ == '__main__':
main()
I hope this helps. Remember its always a good habit to review your code looking for typos and indentation errors.
Bye!

Simple Python chat app with sockets

I'm trying to make a simple client/server chat app in Python with sockets, and eventually turn it into a networked game of Rock, Paper, Scissors.
I found a guide online to create the client/server but I'm having trouble modifying the loops so that each script listens for the other, receives a message, then shows a raw_input that becomes the message sent to the other script, then so on. Here's the code:
client.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.connect((host, port))
while True:
z = raw_input("Enter something for the server: ")
s.send(z)
print s.recv(1024)
server.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
print c.recv(1024)
q = raw_input("Enter something to this client: ")
c.send(q)
Any help? Thank you.
Like #DavidCullen said in the comments, you are halting on the second time through the while loop for the server to accept a new connection.
You can get around that by doing an if-connected check. I also added some print statements so you could clearly debug what is happening.
server.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.bind((host, port))
s.listen(5)
c = None
while True:
if c is None:
# Halts
print '[Waiting for connection...]'
c, addr = s.accept()
print 'Got connection from', addr
else:
# Halts
print '[Waiting for response...]'
print c.recv(1024)
q = raw_input("Enter something to this client: ")
c.send(q)
client.py
#!/usr/bin/python
import socket
s = socket.socket()
host = socket.gethostname()
port = 12221
s.connect((host, port))
print 'Connected to', host
while True:
z = raw_input("Enter something for the server: ")
s.send(z)
# Halts
print '[Waiting for response...]'
print s.recv(1024)

Python - Server and client problems

I'm trying to create a basic server and client script. The idea is that the client can connect to the server and execute commands. Kinda like SSH but very simple. Heres my server code:
import sys, os, socket
host = ''
port = 50103
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)
s.listen(1)
while (1):
conn, addr = s.accept()
print 'New connection from ', addr
try:
while True:
rc = conn.recv(2)
pipe = os.popen(rc)
rl = pipe.readlines()
fl = conn.makefile('w', 0)
fl.writelines(rl[:-1])
fl.close()
except IOError:
conn.close()
And here is my client:
import sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = input('Port: ')
s.connect((host, port))
while (1):
cmd = raw_input('$ ')
s.send(cmd)
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
file.close()
Here is my problem. I start the server and then run the client on the same machine. I enter the port and connect. Then I get the raw_input which is the '$'. If I type a command like 'ls' it just hangs on the client side. I have to exit the server for the client to receive the output of ls. By the way I am running Ubuntu Linux. Not sure if that matters.
When you makefile() on the socket and then use readlines() on it, it will continue until you reach an end of file, which in the socket case is that it closed from the other end.
Using makefile() in this case makes no sense to me, especially since you create it and close it after each command. Just use send() and recv() on both ends.
You probably also want to have some sort of actual "protocol" so the server tells the client "HERE COMES A RESPONSE" and "THIS IS THE END OF THE RESPONSE" so that the client knows. Otherwise it gets hard to know when to stop waiting for more response. :)
Update with an example that works:
server.py:
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 50500))
print("Server started")
s.listen(1)
while True:
print "Accepting"
conn, addr = s.accept()
print 'New connection from ', addr
while True:
try:
rc = conn.recv(1024)
print "Command", rc
if not rc.strip():
continue
if rc.strip() == 'END':
print "Close"
conn.send("**END**")
conn.close()
break
else:
conn.send("This is the result of command %s\n" % rc)
except Exception:
conn.close()
sys.exit()
client.py
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 50500))
while True:
cmd = raw_input('$ ')
s.send(cmd)
result = s.recv(1024)
print result
if result == "**END**":
print "Ending"
break
Well for one thing you're only connecting on the client once and on the server you're closing the socket after every read.
You should take a look at this example.
http://ilab.cs.byu.edu/python/socket/echoserver.html
You're doing quite a few things incorrectly.

Categories