I made a simple text based game and I want to create a multi-player mode to it.
I have a server and two clients:
CLIENT1 ----> SERVER <---- CLIENT2
Client1 sends number 7 to the server and Client2 sends number 5 to the server.
CLIENT1 -- 7 --> SERVER <-- 5 -- CLIENT2
Then the server add this numbers (7+5=12) and send this as a response to the clients.
CLIENT1 <-- 12 -- SERVER -- 12 --> CLIENT2
My question is how can I do this?
UPDATE
I've found a solution:
# -*-coding:utf8;-*-
import socket
import sys
from thread import *
HOST = ''
PORT = 3737
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
def clientthread(conn):
conn.send('Welcome to the server. Type something and hit enter\n')
while True:
data = conn.recv(1024)
return data
conn.close()
n = 0
l = []
while n < 2:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
d = clientthread(conn)
l.append(d)
print l[n]
n = n + 1
player1, player2 = int(l[0]), int(l[1])
Related
Raspberry Pi 3
Python 2.7
Sim800L
Hi!
I am getting errors connecting to the gsm module
Here's the code I got from rhydolabz
import serial
import RPi.GPIO as GPIO
import os, time
GPIO.setmode(GPIO.BOARD)
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=1)
# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
port.write('AT'+'\r\n')
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('ATE0'+'\r\n') # Disable the Echo
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('AT+CMGF=1'+'\r\n') # Select Message format as Text mode
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('AT+CNMI=2,1,0,0,0'+'\r\n') # New SMS Message Indications
rcv = port.read(10)
print rcv
time.sleep(1)
# Sending a message to a particular Number
port.write('AT+CMGS="+6xxxxxxxxx68"'+'\r\n')
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('Hello User'+'\r\n') # Message
rcv = port.read(10)
print rcv
port.write("\x1A") # Enable to send SMS
for i in range(10):
rcv = port.read(10)
print rcv
Here are the errors:
OSError: [Errno 11] Resource temporarily unavailable
raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 5] Input/output error
Sometimes It sends
Hello User
Login incorrect
raspberrypi login:
Sometimes
>
>
>
(100+ more '>')
Hello User
but almost always it doesn't connect and it gives Error 11
Have you experience this too?
Is there a way I can wait for the gsm to connect before I proceed on sending a message?
Did you disconnect the uart from the internal bluetooth and kernel console?
If you don't you will have a problem accessing the device. You need to disable the service that use it:
sudo systemctl disable hciuart
also disable kernel console on that uart eliminating
console=serial0,115200
from kernel command line (/boot/cmdline.txt).And you need to enable two overlays on the device tree (/boot/config.txt) Maybe this can help you:
dtoverlay=pi3-disable-bt
dtoverlay=pi3-miniuart-bt
Complet solution by rasberrypi.org: https://www.raspberrypi.org/documentation/configuration/uart.md
Someone know how can I send string by socket qpython3 android (client) to python2.7 linux (server)?
For python2.7 linux (server) ok, I know, but I dont know how create the client with qpython3 android.
Someone Know?
TKS
My code for server in linux:
import socket
HOST = ''
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
tcp.bind(orig)
tcp.listen(1)
while True:
con, client = tcp.accept()
print 'Connected by', client
while True:
msg = con.recv(1024)
if not msg: break
print cliente, msg
print 'Ending client connection', client
con.close()
For client in android:
import sl4a
import socket
HOST = '127.0.0.1'
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)
print 'Press x to close'
msg = droid.dialogGetInput('Text', 'Input value').result
while msg <> 'x':
tcp.send ((msg).encode('utf-8'))
msg = droid.dialogGetInput('Text', 'Input value').result
tcp.close()
But this send erro on android:
socket.error: [Errno 111] Connection refused
Do U know wats happening?
Tks
It's your loopback address this wont work
HOST = '127.0.0.1'
Instead that use true ip address on network for your host and make sure port of 5000 on server is open already
I was trying to connect a NodeMCU Socket client program to a Python server program, but I was not able to establish a connection.
I tested a simple Python client server code and it worked well.
Python Server Code
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print c.recv(1024)
c.send('Thank you for connecting')
c.close() # Close the connection
Python client code (with this I tested the above code)
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
s.send('Hi i am aslam')
print s.recv(1024)
s.close # Close the socket when done
The output server side was
Got connection from ('192.168.99.1', 65385)
Hi i am aslam
NodeMCU code
--set wifi as station
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--modify according your wireless router settings
wifi.sta.config("xxx", "xxx")
wifi.sta.connect()
function postThingSpeak()
print("hi")
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:connect(12345, "192.168.0.104")
srv:on("connection", function(sck, c)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
end
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip() == nil then
print("Waiting for IP address...")
else
tmr.stop(1)
print("WiFi connection established, IP address: " .. wifi.sta.getip())
print("You have 3 seconds to abort")
print("Waiting...")
tmr.alarm(0, 3000, 0, postThingSpeak)
end
end)
But when I run the NodeMCU there is no response in the Python server.
The Output in the ESPlorer console looks like
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
Waiting for IP address...
WiFi connection established, IP address: 192.168.0.103
You have 3 seconds to abort
Waiting...
hi
Am I doing something wrong or missing some steps here?
Your guidance is appreciated.
After I revisited this for the second time it finally clicked. I must have scanned your Lua code too quickly the first time.
You need to set up all event handlers (srv:on) before you establish the connection. They may not fire otherwise - depending on how quickly the connection is established.
srv = net.createConnection(net.TCP, 0)
srv:on("receive", function(sck, c) print(c) end)
srv:on("connection", function(sck)
print("Wait for connection before sending.")
sck:send("hi how r u")
end)
srv:connect(12345,"192.168.0.104")
The example in our API documentation is wrong but it's already fixed in the dev branch.
import socket
import sys
host='' # Symbolic name meaning all available interfaces
port=7777 #random port
#creating socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "socket created"
#binding
try:
sock.bind((host,port))
except socket.error,msg:
print "Bind failed,Error no:"+str(msg[0])+"error:-"+str(msg[1])
sys.exit()
print "Bind successful"
sock.listen(10)
print "Listening" # it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected.
conn, addr=sock.accept()#accept new connection
print "connected to "+str(addr[0])+":"+str(addr[1])
#receive from client
data=conn.recv(1024)
print "received-"+data
conn.sendall(data*2)
#terminate
conn.close()
sock.close()
the above is the code for receiving data from a client and replying for it.
i used cmd with "telnet localhost 7777" to connect.
then i wanted to send a simple "hello world" message but i just typed "h" and i got a reply and the connection was terminated.
It has worked for me. Is your socketClient working correctly?
import socket
string='hello world'
print type(string)
HOST, PORT = 'localhost', 7777
# SOCK_STREAM == a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.setblocking(0) # optional non-blocking
sock.connect((HOST, PORT))
sock.send(string)
reply = sock.recv(1024) # limit reply to 16K
print(reply)
sock.close()
return reply
I am doing a project in python which I need to implement client creating a ssl connection to a server I also implement.
I used ssl.wrapsocket(), but for some reason when I sniff the traffic using Wireshark I only see the TCP handshake.
Here is my client side code:
import socket
import ssl
import os
SERVER_ADDRESS = ('**********', 10000)
#open a TCP socket
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.settimeout(20000)
#connect to the server
client_sock.connect(SERVER_ADDRESS)
#start ssl handshake with the server
keyfile = os.path.dirname(__file__).replace('/', '\\') + '\\server.key'
certfile = os.path.dirname(__file__).replace('/', '\\') + '\\server.crt'
cli_ssl_sock = ssl.wrap_socket(
sock=client_sock,
certfile=certfile,
keyfile=keyfile,
server_side=False,
ssl_version=ssl.PROTOCOL_SSLv23,
ca_certs=None,
do_handshake_on_connect=False,
suppress_ragged_eofs=True,
)
cli_ssl_sock.do_handshake()
Here is my server side code:
import socket
import ssl
SERVER_ADDRESS = ('**********', 10000)
keyfile = '/root/Desktop/server.key'
certfile = '/root/Desktop/server.crt'
#create TCP socket
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#bind the socket
server_sock.bind(SERVER_ADDRESS)
#listen
server_sock.listen(5)
print 'server is listening ...'
#receiving connections
while True:
conn_sock, client_address = server_sock.accept()
print 'new connection from : ' + str(client_address)
ssl_server_sock = ssl.wrap_socket(
sock=conn_sock,
certfile=certfile,
keyfile=keyfile,
server_side=True,
ssl_version=ssl.PROTOCOL_SSLv23,
ca_certs=None,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
)