Related
My target is print the message from function result on the client's screen. But only ONE client can received the message...
The part of client.py is here
def PlayGame(clientSocket, msg):
invalid = "NO!"
if ("/guess " in msg):
msg1 = msg.split(" ")[1]
print("Hi1\n")
if msg1 == "true" or msg1 == "false":
print("Hi11")
clientSocket.send(msg1.encode())
print(clientSocket.recv(1024).decode())
print("!")
return '1'
else:
clientSocket.send(invalid.encode())
print(clientSocket.recv(1024).decode())
print("2")
return '2'
elif msg == "":
return '2'
else:
clientSocket.send(invalid.encode())
print(clientSocket.recv(1024).decode())
print("3")
return '2'
def main(argv):
msg=""
while (PlayGame(clientSocket, msg)!=1):
msg = input()
Any part of the server.py
guess_box = []
guess = bool(random.randint(0, 1))
def result(connectionSocket, guess_box, addr, addr_l):
a = 0
if(guess_box[0] == guess_box[1]):
msg = "Tie!!"
connectionSocket.send(msg.encode())
return '2'
elif(guess_box[0] == guess):
msg = "Player 1 Wins!"
a+=1
connectionSocket.send(msg.encode())
return '2'
elif(guess_box[1] == guess):
msg = "Player 2 Wins!"
a+=1
connectionSocket.send(msg.encode())
return '2'
def TF(connectionSocket, var, guess_box, addr, addr_l):
msg = connectionSocket.recv(1024).decode()
print("recv:",msg)
if(msg == 'true'):
msg = 'True'
var = str(var)
msg = bool(msg == var)
guess_box.append(msg)
return 'ok'
elif(msg == 'false'):
msg = 'False'
var = str(var)
msg = bool(msg == var)
guess_box.append(msg)
return 'ok'
else:
print(msg)
statement = "4002 Unrecognized message!!"
connectionSocket.send(statement.encode())
return 'again'
class ServerThread(threading.Thread):
def __init__(self, client):
threading.Thread.__init__(self)
self.client = client
def run(self):
...
print("guess is:", guess)
while (len(guess_box) != 2):
TF(connectionSocket, guess, guess_box, addr, addr_l)
print("start")
result(connectionSocket, guess_box, addr, addr_l)
...
Regarding only the one problem you address:
print the message from function result on the client's screen. But only ONE client can received the message
The problem comes from the use of a different thread for each client. The thread which receives a guess as first stays in its
while (len(guess_box) != 2):
print(guess_box)
TF(connectionSocket, guess, guess_box)
loop and waits for another message, which doesn't come. The thread which receives a guess as second sends the result to its own client only.
I don't think there's a sensible way to fix this while keeping this dthreaded approach.
Can I change the structure of my code by using those functions I implemented?
Here's a substitute for the while True loop in server_run that doesn't require changes in those functions other than server_run.
from select import select
connections = []
room_connection = {}
for reads in iter(lambda: select([serverSocket]+connections, [], [])[0], []):
for ready in reads: # for each socket which select reports is readable
if ready == serverSocket: # it's the server socket, accept new client
connectionSocket, addr = serverSocket.accept()
connections.append(connectionSocket)# store the connection socket
while RecvFromClient(connectionSocket) == "NO": pass
else: # message (or disconnect) from a client
try: var = GameHallMsg(ready, ready, connections)
except socket.error: var = 'bye'
if var == 'bye': # client finished, remove from list
connections.remove(ready)
ready.close()
elif var == 'wait': # store first player's connection
room_connection[current_rm_num.pop()] = ready
elif var == 'NO':
rtn_msg_4 = "4002 Unrecognized message"
ready.send(rtn_msg_4.encode())
elif var == 'jump':
readyroom = current_rm_num.pop()
# find and notify other player in the room
other = room_connection.pop(readyroom)
rtn_msg_2 = "3012 Game started. Please guess true or false"
other.send(rtn_msg_2.encode())
print("guess is:", guess)
# query and inform both players
guess_box = []
while TF(ready, True, guess_box) != 'ok': pass
while TF(other, True, guess_box) != 'ok': pass
result(ready, guess_box, ('', 0), [0])
result(other, guess_box, ('', 1), [0, 1])
room[readyroom] = 0
I am having a problem with my program where my server receives data that I am NOT sending from my client
Connection from: ('192.168.0.17', 58167)
data recieved : __UserLogin123__
User Login requested
James Green at recieve login
James Green in accessCodes
93
{93: ['James', 'Green']}
Found
User Found
3
data recieved : __QUIT____CHECK_SCORE__
Incorrect code received
done
Connection from: ('192.168.0.17', 58182)
data recieved : __UserLogin123__
User Login requested
James Green at recieve login
James Green in accessCodes
93
{93: ['James', 'Green']}
Found
User Found
3
data recieved : __QUIT____CHECK_SCORE__
Incorrect code received
the last "data recieved : QUIT___CHECK_SCORE" makes absolutely no sense, I use codes to access methods from classes which will send certain types of data telling the server if i want to (for example) add a user to a database, and it does this by accessing a dictionary storing methods with string keys.
Here is the "handler" and "main" from my client:
def Main():
global s
host = "192.168.0.17"
port = 5000
ID = "__UserLogin123__"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((host, port))
s.send(str.encode(ID))
setupCheck = s.recv(2048).decode()
time.sleep(1)
if setupCheck == "__dataReceived__":
username = input("Enter username : ")
password = input("Enter password : ")
userDetails = (username, password)
dataString = pickle.dumps(userDetails)
s.send(dataString)
access = s.recv(2048).decode()
print(access)
if access == "__ACCESS_GRANTED__":
permissionLvl = s.recv(2048).decode()
print(permissionLvl)
if permissionLvl == "1":
ClientUser = User(username,password)
elif permissionLvl == "2":
ClientUser = Admin(username,password)
elif permissionLvl == "3":
ClientUser = HeadAdmin(username,password)
else:
print("SOMETHING WRONG SOMETHING WROGN")
time.sleep(3)
handler(ClientUser)
else:
print("Incorrect details provided")
def handler(ClientUser):
function_dict = {"__QUIT__": ClientUser.quit(), "__PLAY_GAME__": ClientUser.playGame(),
"__CHECK_SCORE__": ClientUser.checkScore(),"__CHECK_USERS__": ClientUser.checkUsers(),
"__ADD_ASSIGNMENT__": ClientUser.addAssignment(),"__REMOVE_ASSIGNMENT__": ClientUser.removeAssignment(),
"__EDIT_ASSIGNMENT__": ClientUser.editAssignment(), "__ADD_USER__": ClientUser.addUser(),
"__EDIT_USER__": ClientUser.editUser(), "__REMOVE_USER__": ClientUser.removeUser(),
"__CREATE_GROUP__": ClientUser.createGroup()}
while True:
checkDataReady = s.recv(2048).decode()
print(checkDataReady)
if checkDataReady == "__dataExchangeReady__":
print("Available Commands:")
ClientUser.availableCommands()
commandChoice = ""
while commandChoice not in choices:
while True:
try:
commandChoice = int(input("Please enter your choice (number) \n-> "))
except ValueError:
print("Please only enter integers")
finally:
if commandChoice > 14 or commandChoice < 0:
print("Please only enter one of the numbers listed")
else:
break
commandChoice = choices[commandChoice]
print(commandChoice)
checkString = "Are you sure you want to : " + commandChoice + "? (Y/N) -> "
check = input(checkString)
if check.upper() == "N":
commandChoice = ""
print("executing function")
function_dict[commandChoice]
and here is some server side code that I think is affiliated with the problem:
def handler(conn, addr):
print("done")
print("Connection from: " + str(addr))
dbSetup()
while True:
time.sleep(1)
data = conn.recv(2048).decode()
print("data recieved : " + data)
if data == "__QUIT__" or not data:
print("Connection closed")
print("Connection Closed by", addr[0], ":", addr[1])
break
elif data in accessCodes:
accessCodesHandler(data)
elif data in commandCodes:
commandCodesHandler(data)
else:
print("Incorrect code received")
break
conn.send(str.encode("__dataExchangeReady__"))
conn.close()
def accessCodesHandler(accessCode):
if accessCode == accessCodes[0]:
print("User Login requested")
username, password = receiveLoginDetails()
print(username,password, "in accessCodes")
userCheck = getUser_InHash(username, password)
if userCheck == True:
userPermissionLvl = str(getUser_InUserDb(username,"")[2])
print("User Found")
conn.send(str.encode("__ACCESS_GRANTED__"))
time.sleep(1)
print(userPermissionLvl)
conn.send(str.encode(userPermissionLvl))
else:
print("User not found")
conn.send(str.encode("__AccessDenied__"))
else:
print("Head admin setup protocol executed")
username, password = receiveLoginDetails()
addUser_InHash(username, password, 3)
I can see no reason why my server would ouput "QUIT__CHECK_SCORE" as i dont send any data that says that explicitly, my error code for client side is:
Enter username : James
Enter password : Green
__ACCESS_GRANTED__
3
James
Green
Traceback (most recent call last):
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 197, in <module>
Main()
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 153, in Main
handler(ClientUser)
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 161, in handler
"__ADD_ASSIGNMENT__": ClientUser.addAssignment(),"__REMOVE_ASSIGNMENT__": ClientUser.removeAssignment(),
File "C:/Users/Green/Desktop/Py Proj/Project_Client.py", line 37, in removeAssignment
s.send(str.encode("__REMOVE_ASSIGNMENT__"))
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
Process finished with exit code 1
Sorry if this isnt enough information, I really dont know what is wrong with the program. Thanks in advance for any help
Your dictionary initialization code is suspect.
The following actually invokes funca() and stores its return value as the value associated with the key 'a':
d = { 'a': funca() }
If you want to store the funca function itself, for later lookup and invocation, then use:
d = { 'a': funca }
I am making a hangman game. I am trying to send to the server that if lose == 7, then loseGame = true. And in the client Side, if loseGame is true, to print out that the game has been lost. I matched the send and recv, but it is not working and keeps on asking for input for guess the letter. Do you know what I am doing wrong?
I put THIS IS WHERE THE PROBLEM IS where I believe the problem is.
Thank you!
Server:
import sys
# Import socket library
from socket import *
if sys.argv.__len__() != 2:
serverPort = 5895
# Get port number from command line
else:
serverPort = int(sys.argv[1])
# Choose SOCK_STREAM, which is TCP
# This is a welcome socket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# Start listening on specified port
serverSocket.bind(('', serverPort))
# Listener begins listening
serverSocket.listen(1)
print("The server is ready to receive")
#Set secret word
word = 'arkansas'
linesForString = ''
#Prints out number of letters
for x in word:
linesForString += '_'
newWord = 'arkansas'
# Wait for connection and create a new socket
# It blocks here waiting for connection
connectionSocket, addr = serverSocket.accept()
win = ' '
#Sends lines of words
linesInBytes = linesForString.encode('utf-8')
connectionSocket.send(linesInBytes)
lose = 0
while 1:
l = list(word)
list2 = list(linesForString)
win = False
while 1:
while win == False:
losee = 0
# Receives Letter
letter = connectionSocket.recv(1024)
letterString = letter.decode('utf-8')
for x in range(len(list2)):
if(list2[x] == '_'):
if(letterString == l[x]):
list2[x] = letterString
for x in range(len(word)):
if(letterString == word[x]):
losee = -1
if (losee != -1):
lose += 1
print(lose)
newWord = "".join(list2)
#Sends newWord
newWordInBytes = newWord.encode('utf-8')
connectionSocket.send(newWordInBytes, lose)
if(newWord == 'arkansas'):
win = True
winGame = 'You have won the game'
winGameInBytes = winGame.encode('utf-8')
connectionSocket.send(winGameInBytes)
connectionSocket.close()
if(lose == 7):
loseGame = 'true'
connectionSocket.close()
else:
loseGame = 'false'
#THIS IS WHERE THE PROBLEM IS
loseGameInBytes = loseGame.encode('utf-8')
connectionSocket.send(loseGameInBytes)
# Close connection to client but do not close welcome socket
connectionSocket.close()
Client:
import sys
# Import socket library
from socket import *
if sys.argv.__len__() != 3:
serverName = 'localhost'
serverPort = 5895
# Get from command line
else:
serverName = sys.argv[1]
serverPort = int(sys.argv[2])
# Choose SOCK_STREAM, which is TCP
clientSocket = socket(AF_INET, SOCK_STREAM)
# Connect to server using hostname/IP and port
clientSocket.connect((serverName, serverPort))
#Recieves lines of words
linesInBytes = clientSocket.recv(1024)
lines = linesInBytes.decode('utf-8')
for x in lines:
print(x, end = " ")
while 1:
# Get letter from user
print('\n')
letter = input('Guess a letter: ')
# Sends letter
letterBytes = letter.encode('utf-8')
clientSocket.send(letterBytes)
#Recieves newWord
newWordInBytes = clientSocket.recv(1024)
newWord = newWordInBytes.decode('utf-8')
for x in newWord:
print(x, end = " ")
print(" ")
if(newWord == 'arkansas'):
winGameInBytes = clientSocket.recv(1024)
winGame = winGameInBytes.decode('utf-8')
print(winGame)
clientSocket.close()
break
#THIS IS WHERE THE PROBLEM IS
loseGame = " "
loseGameInBytes = clientSocket.recv(1024)
loseGame = loseGame.encode('utf-8')
if(loseGame == "true"):
print('You have lost the game!')
clientSocket.close()
A couple of things I had issues with until I could get it working:
1. notice when you take input use raw_input, otherwise it crashed for me.
2.where you thought there was an issue in the server there really was one. You accidentally close connection and then send once the game is lost
3. in the client you have loseGame = loseGame.encode('utf-8') instead of loseGame = loseGameInBytes.encode('utf-8')
4. I change the print statements to print(str(x) + " "), because yours gave me issues
This is the code after I fixed it. Notice I changed and added breaks in the server that aren't necessary and they will cause the server to close at the end of a single game.
server code:
import sys
# Import socket library
from socket import *
if sys.argv.__len__() != 2:
serverPort = 5895
# Get port number from command line
else:
serverPort = int(sys.argv[1])
# Choose SOCK_STREAM, which is TCP
# This is a welcome socket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# Start listening on specified port
serverSocket.bind(('', serverPort))
# Listener begins listening
serverSocket.listen(1)
print("The server is ready to receive")
#Set secret word
word = 'respecttheplatypus'
linesForString = ''
#Prints out number of letters
for x in word:
linesForString += '_'
newWord = 'respecttheplatypus'
# Wait for connection and create a new socket
# It blocks here waiting for connection
connectionSocket, addr = serverSocket.accept()
win = ' '
#Sends lines of words
linesInBytes = linesForString.encode('utf-8')
connectionSocket.send(linesInBytes)
lose = 0
while 1:
l = list(word)
list2 = list(linesForString)
win = False
while 1:
while win == False:
losee = 0
# Receives Letter
letter = connectionSocket.recv(1024)
letterString = letter.decode('utf-8')
for x in range(len(list2)):
if(list2[x] == '_'):
if(letterString == l[x]):
list2[x] = letterString
for x in range(len(word)):
if(letterString == word[x]):
losee = -1
if (losee != -1):
lose += 1
print(lose)
newWord = "".join(list2)
#Sends newWord
newWordInBytes = newWord.encode('utf-8')
connectionSocket.send(newWordInBytes, lose)
if(newWord == 'respecttheplatypus'):
win = True
winGame = 'You have won the game'
winGameInBytes = winGame.encode('utf-8')
connectionSocket.send(winGameInBytes)
connectionSocket.close()
else:
if(lose == 7):
loseGame = 'true'
loseGameInBytes = loseGame.encode('utf-8')
print(loseGame)
connectionSocket.send(loseGameInBytes)
connectionSocket.close()
break
else:
loseGame = 'false'
#THIS IS WHERE THE PROBLEM IS
loseGameInBytes = loseGame.encode('utf-8')
print(loseGame)
connectionSocket.send(loseGameInBytes)
break
break
client code:
import sys
# Import socket library
from socket import *
if sys.argv.__len__() != 3:
serverName = 'localhost'
serverPort = 5895
# Get from command line
else:
serverName = sys.argv[1]
serverPort = int(sys.argv[2])
# Choose SOCK_STREAM, which is TCP
clientSocket = socket(AF_INET, SOCK_STREAM)
# Connect to server using hostname/IP and port
clientSocket.connect((serverName, serverPort))
#Recieves lines of words
linesInBytes = clientSocket.recv(1024)
lines = linesInBytes.decode('utf-8')
for x in lines:
print(str(x) + " "),
while 1:
# Get letter from user
print('\n')
letter = raw_input('Guess a letter: ')
# Sends letter
letterBytes = letter.encode('utf-8')
clientSocket.send(letterBytes)
#Recieves newWord
newWordInBytes = clientSocket.recv(len(linesInBytes))
newWord = newWordInBytes.decode('utf-8')
for x in newWord:
print(str(x) + " "),
print(" ")
if(newWord == 'respecttheplatypus'):
winGameInBytes = clientSocket.recv(1024)
winGame = winGameInBytes.decode('utf-8')
print(winGame)
clientSocket.close()
break
#THIS IS WHERE THE PROBLEM IS
loseGame = " "
loseGameInBytes = clientSocket.recv(1024)
loseGame = loseGameInBytes.encode('utf-8')
print("lose game is" + str(loseGame))
if(loseGame == "true"):
print('You have lost the game!')
clientSocket.close()
I'm writing a socket communication program, I have a main thread, and another thread trying to sock.recv()
when it does recieve bytes, it works as it needs, it goes to the right function, which at the end prints, and then the thread listens again to bytes (as wanted).
the problem is that the program won't print until I press enter...
if it matters i'm getting input at the same time in the main thread but it shouldn't matter.
note - the bytes are sent like this:
int (4 bytes) - msg type (string to print is 2)
int (4 bytes) - length of text to print
string ( bytes) - actual text
full code:
import socket
import time
import struct
import threading
import sys
PORT = 54321
def try_to_connect(ip):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
socket.IPPROTO_TCP)
sock.settimeout(1)
try:
sock.connect((ip, PORT))
return sock
except:
return False
def text_parse(text, msg_id):
byte_text = bytes(text, "utf-8")
return struct.pack("II%ds" % len(byte_text), msg_id, len(byte_text), byte_text)
def main(sock):
global file_name
print("connected succefuly. to run a command, write $<command> (no space)\nto request a file, enter file path.\nto exit this program enter exit.")
inputed_text = ''
while True:
inputed_text = input()
if inputed_text == '':
pass
elif inputed_text == "exit":
return
elif inputed_text[0] == "$":
sock.send(text_parse(inputed_text[1:], 0))
else:
file_name = inputed_text
sock.send(text_parse(inputed_text, 1))
def print_string(message, msg_len):
text = struct.unpack("%ds" % msg_len, message)[0].decode("utf-8")
sys.stdout.write(text)
sys.stdout.flush()
def copy_file(message):
global file_name
final_file = open(file_name, "wb")
final_file.write(message)
final_file.close()
def recieve_loop(sock):
while True:
try:
header = sock.recv(8)
if not header: break
msg_type = struct.unpack("I", header[:4])[0]
msg_len = struct.unpack("I", header[4:8])[0]
print(msg_type)
print(msg_len)
message = sock.recv(msg_len)
if msg_type == 2:
print_string(message, msg_len)
elif msg_type == 3:
copy_file(message)
except socket.timeout:
pass
if __name__ == "__main__":
print("welcome to remote desktop program.\nto connect to your computer, enter it's ip.\nto exit enter exit")
text_input = "b,kjhkf"
while True:
text_input = input()
if text_input == "exit":
exit()
else:
sock = try_to_connect(text_input)
if sock:
socket_recieve_thread = threading.Thread(target = recieve_loop, args = [sock])
socket_recieve_thread.start()
main(sock)
socket_recieve_thread.join()
else:
print("the computer is not online")
I've been working on a python game in my spare time, and I've run into a problem. I'm working with sockets using the basic threads module, and it works fine when I connect to the server file with one client. But more than that, and any that connect after the first freezes up the server and the first client.
Here is the code for the server
import socket
import random
import thread
from saveState import Save
from grid import Grid
import time
players = 0
save = Save()
grid = Grid()
def ready(c):
ready = raw_input("Are you ready to play?\n")
if(ready == "yes" or ready == "y"):
grid.makeGrid()
c.send("ready")
def clientThread(conn,players):
while True:
print "taking requests"
request = conn.recv(1024)
segments = request.split(",,")
if(segments[0] == "0" and players<200):
print "registering player", addr
serial = random.choice(list(range(999999)))
conn.send("{}".format(serial))
save.players[serial] = segments[2:]
print save.players[serial][9]
players+=1
elif(segments[0] == "3"):
if(segments[2] == "land"):
conn.send("{},,{},,{},,{}".format(grid.getLandType(int(save.players[serial][9]),int(save.players[serial][10])), grid.getDesc(int(save.players[serial][9]),int(save.players[serial][10])),int(save.players[serial][9]),int(save.players[serial][10])))
elif(segments[0]=="2"):
if(segments[2]=="playerX" and int(segments[3])==-1):
save.players[serial][9] = int(save.players[int(serial)][9])-1
elif(segments[2]=="playerX"):
save.players[serial][9] = int(save.players[int(serial)][9])+1
if(segments[2]=="playerY" and int(segments[3])==-1):
save.players[serial][10] = int(save.players[int(serial)][10])-1
elif(segments[2]=="playerY"):
save.players[serial][10] = int(save.players[int(serial)][10])+1
elif(segments[0]=="4"):
alreadySent = []
for m in grid.monsters:
if(m.X==save.players[int[segment[1]]][9] and m.Y==save.players[int[segment[1]]][10] and alreadySent[m]==False):
conn.send("{},,{}".format(m.name, True))
elif(time.clock == 60*60*(12+8)):
conn.send("{},,{}".format("You see the sun set on the horizon. Monsters will be more aggressive now.", False))
else:
print "sorry, there is an inconsistency in the request or the queue is full."
try:
#start up socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostbyname(socket.gethostname())
print name
port = input("select port\n")
s.bind((name, port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#listen for any attempts to connect to the api
#if anyone connects, give them a serial number and add their data to a storage file
while True:
s.listen(5)
c,addr = s.accept()
thread.start_new_thread(ready,(c,))
thread.start_new_thread(clientThread,(c, players))
conn.close
sock.close
except socket.error:
print " either the server port is closed or in use. try again"
and the client
import random
from grid import Grid
from player import Player
from descriptions import Descriptions
import socket
import time
import thread
description = Descriptions()
def descisionHandler(s,serial):
while True:
s.send("{},,{},,{}".format(3,serial,"land"))
response = s.recv(1024).split(",,")
print "you are on a {} tile \n {} \n {} \n {}".format(response[0], response[1],response[2], response[3])
action=raw_input("What Will You Do?\n")
try:
if(action == "west" and player.locX>0):
s.send("{},,{},,{},,{}".format(2,serial,"playerX",-1))
time.sleep(0.5)
elif(action == "east" and player.locX<199):
s.send("{},,{},,{},,{}".format(2,serial,"playerX",1))
time.sleep(0.5)
elif(action == "north" and player.locY>0):
s.send("{},,{},,{},,{}".format(2,serial,"playerY",-1))
time.sleep(0.5)
elif(action == "south" and player.locY<199):
s.send("{},,{},,{},,{}".format(2,serial,"playerY",1))
time.sleep(0.5)
# elif(action == "attack" and monster_data[1]):
# print "The {} wakes up! A battle begins!".format(monster_data[0])
elif(action == "profile"):
print " You are {} \n {} \n your role is {} \n you have an attack of {} \n a defense of {} \n a speed of {} \n and {} hitpoints \n attacks: {} \n you are located at {} {}".format(player.name,
player.backstory,player.role,player.attack,player.defense,player.speed, player.hitpoints, player.attacks, player.locX, player.locY)
elif(action == "exit"):
break
except IndexError:
pass
def eventHandler(s,serial):
while True:
s.send("{},,{}".format(4,serial))
response = s.recv(1024).split(",,")
print response[0]
return bool(response[1])
while True:
try:
print "\nWelcome to Overseer! We need a few things before we begin\n"
name = raw_input("What is your name?\n")
backstory = raw_input("What is in your past: choose one \n chosen \n magician \n poet\n")
role = raw_input("what is your class: choose one \n Warrior \n Mage \n Rougue \n Bard\n")
player = Player(name,description.player_backstory[backstory], role, 5,5,5,10, {"scrap": 10}, random.choice(list(range(200))), random.choice(list(range(200))))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("what host are you connecting to?")
port = input("what port?\n")
s.connect((host,port))
print "connection successful."
time.sleep(5)
s.send("{},,{},,{},,{},,{},,{},,{},,{},,{},,{},,{},,{},,{}".format(0,0,name,backstory,role,5,5,5,5,10,player.attacks,player.locX,player.locY))
serial = s.recv(1024)
print "You're serial number is {}".format(serial)
while(s.recv(1024) != "ready"):
pass
break
except socket.error:
print "server is not running or is busy. please try again."
eventThread = thread.start_new_thread(eventHandler,(s,serial))
descisionThread = thread.start_new_thread(descisionHandler,(s,serial))
while 1:
pass
I did a bit of research and my best guess is that I need to use locks from the threading module, but I'm not sure. any suggestions?
Thanks in advance!
So the issue was the console input, as theSmallNothing said. There wasn't really a way around this limitation without serious hacking, so I proposed to improvise. My solution was to create a web app with python instead of using a console. There were a few advantages to this.
the server can handle multiple inputs at a time easily
things can happen while input is being entered(the solution to my problem)
no files need be downloaded for the user as everything can be accessed simply by entering the web address.
While not a perfect solution, sometimes finding an alternative is the next best thing.
Thanks all for your awesome help!