Run more than one thread in micropython(pico w) - micropython

i am gettinig this error below when i try to run the second thread on my pico w.
Traceback (most recent call last):
File "<stdin>", line 114, in <module>
OSError: core1 in use
I am trying to display some content in one thread, and in another, server a simple web page with the same content.
"""BME688 / BME680 demo
This demo will work for both the BME680 and BME688.
"""
print("lets import and use the libraries")
import time
from time import sleep
import network
import socket
import _thread
from breakout_bme68x import BreakoutBME68X, STATUS_HEATER_STABLE
from pimoroni_i2c import PimoroniI2C
from picographics import PicoGraphics, DISPLAY_LCD_240X240, PEN_P8
display = PicoGraphics(display=DISPLAY_LCD_240X240, pen_type=PEN_P8)
display.set_backlight(1.0)
WIDTH, HEIGHT = display.get_bounds()
ssid = 'netgear_2.4g' #Your network name
password = '9xc4prce' #Your WiFi password
print("setting pin breakouts etc")
PINS_BREAKOUT_GARDEN = {"sda": 4, "scl": 5}
PINS_PICO_EXPLORER = {"sda": 20, "scl": 21}
print("finish setting pins and now set i2c")
i2c = PimoroniI2C(**PINS_BREAKOUT_GARDEN)
print("i2c set and now set bme")
bme = BreakoutBME68X(i2c)
print("bme set")
# If this gives an error, try the alternative address
# bme = BreakoutBME68X(i2c, 0x77)
temperatureReadingData = ["","0.0c"]
print("Testing sensors on the while loop")
def connect():
#Connect to WLAN
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while wlan.isconnected() == False:
print('Waiting for connection...')
sleep(1)
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
def open_socket(ip):
# Open a socket
address = (ip, 80)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
return connection
def readTemperature():
temperature, pressure, humidity, gas, status, _, _ = bme.read()
heater = "Stable" if status & STATUS_HEATER_STABLE else "Unstable"
temperatureReadingData[0] = "Temperature is {:0.2f}c, Pressure is {:0.2f}Pa, humidity is {:0.2f}%, gas is {:0.2f} Ohms, Heater: {}".format(temperature, pressure, humidity, gas, heater)
temperatureReadingData[1] = "{:0.2f}c".format(temperature)
def webpage(reading):
#Template HTML
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Pico W Weather Station</title>
<meta http-equiv="refresh" content="10">
</head>
<body>
<p>{reading}</p>
</body>
</html>
"""
return str(html)
def serve():
#Start a web server
ip = connect()
connection = open_socket(ip)
while True:
client = connection.accept()[0]
request = client.recv(1024)
request = str(request)
html = webpage(temperatureReadingData[0])
client.send(html)
client.close()
def displayTemp():
while True:
readTemperature()
print("display temp" + temperatureReadingData[1])
display.clear()
display.set_pen(15)
display.text(temperatureReadingData[1], 0, 0, scale=4)
display.update()
time.sleep(1.0)
if __name__ == "__main__":
try:
tempDisplay = _thread.start_new_thread(displayTemp, ())
webServer = _thread.start_new_thread(serve, ())
except KeyboardInterrupt:
machine.reset()

Related

Why does kivy keep freezing when using python sockets?

I'm working on a basic client-server desktop app project using kivy & sockets & threading.
The client & server work on it's own, however when I try to integrate it with kivy, python & kivy don't want to respond & yet no definitive error pops up.
Could i have some ideas as to how to fix this?
This is the code that freezes when i run it, if i take away the import server_sock it works as a general gui and doesnt freeze.
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
import server_sock
import sys
kivy.require("2.1.0") #latest version
class ConnectPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text="IP:"))
self.ip = TextInput(multiline=False)
self.add_widget(self.ip)
self.add_widget(Label(text="PORT:"))
self.port = TextInput(multiline=False)
self.add_widget(self.port)
self.add_widget(Label(text="USERNAME:"))
self.user = TextInput(multiline=False)
self.add_widget(self.user)
self.join = Button(text="Join")
self.join.bind(on_press=self.join_button)
self.add_widget(Label())
self.add_widget(self.join)
def join_button(self, instance):
port = self.port.text
ip = self.ip.text
user = self.user.text
info = f"Attempting to join {ip}:{port} as {user}"
chat_app.info_page.update_info(info)
chat_app.screen_manager.current = "Info"
Clock.shedule_once(self.connect,1)
def connect(self, _):
port = int(self.port.text)
ip = self.ip.text
user = self.user.text
try:
server_sock.connect(ip, port)
chat_app.create_chat_page()
chat_app.screen_manager.current = "Chat"
except:
show_error(message="not gonna happen")
class InfoPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.message = Label(halign="center", valign="middle", font_size="30")
self.message.bind(width=self.update_text_width)
self.add_widget(self.message)
def update_info(self,message):
self.message.text = message
def update_text_width(self, *_):
self.message.text_size = (self.message.width*0.9, None)
class ChatPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.add_widget(Label(text="Hey at least it works till now"))
class ChatApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.connect_page = ConnectPage()
screen = Screen(name="Connect")
screen.add_widget(self.connect_page)
self.screen_manager.add_widget(screen)
self.info_page = InfoPage()
screen= Screen(name="Info")
screen.add_widget(self.info_page)
self.screen_manager.add_widget(screen)
return self.screen_manager
def create_chat_page(self):
self.chat_page = ChatPage()
screen = Screen(name="Chat")
screen.add_widget(self.chat_page)
self.screen_manager.add_widget(screen)
def show_error(message):
chat_app.info_page.update_info(message)
chat_app.screen_manager.current = "Info"
Clock.shedule_once(sys.exit, 10)
if __name__ == "__main__":
chat_app =ChatApp()
chat_app.run()
This is the server_sock file
import socket
import threading
import socket
HOST = '127.0.0.1'
PORT = 55555
server = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
)
try:
server.bind((HOST, PORT))
except:
print(f'unable to bind to {HOST} and {PORT}')
server.listen()
print(f"Listening for connections on {HOST}: {PORT}")
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def message_recv(client):
while True:
try:
message = client.recv(2048)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
nickname = nicknames[index]
broadcast(f'{nickname} left the chat'.encode('ascii'))
nicknames.remove(nickname)
break
def recieve():
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
client.send("SOMETHING".encode('ascii'))
nickname = client.recv(2048).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print(f"Nickname of the client is {nickname}")
broadcast(f"{nickname} joined the chat".encode('ascii'))
client.send("Connected to the server".encode('ascii'))
thread = threading.Thread(target=message_recv, args=(client,))
thread.start()
print("Server is listening")
recieve()

How to make this work in parallel with _thread on a pico w and micropython?

So, im trying to make a webserver and processing data with a pico in parallel, my goal is to reach the pico from my browser using the local network ip to see in what step the pico is working and what data is on the current loop, however i have two issues and i have no idea how to make it work:
When running the two process in parallel using _thread, the webserver function hangs until the dataprocess function finish, so i cant see in realtime what is going on, the webserver respond only when the other process is finished and it hangs again, i need to press f5 on my browser at the exact time when the dataprocess function finish and start again only to see part of the process because it hangs if i refresh my browser to see the progress
When running the webserver, the urequets.get function of the dataprocess function does not work, it throws [Errno 103] ECONNABORTED
Here is the part of my code that is not working:
import utime, machine, urequests, json, network, socket, _thread
led = machine.Pin("LED", machine.Pin.OUT)
def connect():
global wlan
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID", "PASSS")
while wlan.isconnected() == False:
print("Connecting...")
led.off()
utime.sleep_ms(100)
led.on()
utime.sleep_ms(100)
led.off()
utime.sleep_ms(100)
led.on()
utime.sleep_ms(100)
led.on()
ip = wlan.ifconfig()[0]
print(f'Connected on {ip}')
return ip
def open_socket(ip):
address = (ip, 80)
connection = socket.socket()
connection.bind(address)
connection.listen(1)
return connection
def webpage(steps):
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>Pico 2</title>
</head>
<body>
<p>{steps}</p>
</body>
</html>
"""
return str(html)
def pushgetdata():
while wlan.isconnected() == True:
try:
global steps
led.off()
utime.sleep_ms(300)
led.on()
steps = "Step 1: Reading values from sensor one...<br>"
#function to read data from one sensor here
#...
#...
#...
led.off()
utime.sleep_ms(100)
led.on()
steps = steps + "Step 2: Reading values from sensor two...<br>"
#function to read data from other sensor here
#...
#...
#...
led.off()
utime.sleep_ms(100)
led.on()
steps = steps + "Step 3: Pushing and getting results...<br>"
jsondata = urequests.get("https://xxx.xxx.xxx/api/?device=pico2&sensor1=valulesfromsensor1&sensor2=valuesfromsensor2")
proceseddata = jsondata.json()
steps = steps + proceseddata + "<br>"
steps = steps + "Step 4: Doing things with results...<br>"
#function to do conditions and things with results...
#...
#...
#...
jsondata.close()
steps = steps + "Step 5: Finished, sleeping for the next round...<br>"
utime.sleep_ms(100)
led.off()
utime.sleep_ms(100)
led.on()
utime.sleep(900)
except OSError as e:
steps = steps + e
def serve(connection):
while True:
try:
client, addr = connection.accept()
print('client connected from', addr)
request = client.recv(1024)
request = str(request)
html = webpage(steps)
client.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
client.send(html)
client.close()
except OSError as e:
client.close()
def webserver():
ip = connect()
connection = open_socket(ip)
_thread.start_new_thread(serve,(connection,))
try:
webserver()
pushgetdata()
except KeyboardInterrupt:
machine.reset()
I'm not sure exactly what's going on with your code, but using the same threading idea, please find here my solution for a similar problem I've encountered today if it helps.
from machine import Pin
from time import sleep
import wlan_data, network
import socket, _thread
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wlan_data.SSID, wlan_data.PASSWORD)
print("WLAN is connected: " + str(wlan.isconnected()))
page = open("index.html", "r")
html = page.read()
page.close()
sta_if = network.WLAN(network.STA_IF)
print(sta_if.ifconfig()[0])
def setUpSocket():
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(1)
return s
def serve(s):
while True:
try:
cl, addr = s.accept()
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = html
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()
except OSError as e:
cl.close()
def webserver():
s = setUpSocket()
_thread.start_new_thread(serve,(s,))
webserver()
led = machine.Pin("LED", machine.Pin.OUT)
led.toggle()
while 1:
led.toggle()
sleep(10)
_thread library is experimental and buggy. From the micropython documentation https://docs.micropython.org/en/latest/library/_thread.html
This module is highly experimental and its API is not yet fully settled and not yet described in this documentation.
From my own testing, some of the functionality works for a while, then you might add another import and things stop working. Best to steer clear until it is no longer an experimental feature.

Dual core on Raspberry Pi PICO W with MicroPython

I have an issue with running part of a code to be more specific defined as new thread CoreTask().
I have no idea why I cannot turn on/off built-in LED. The rest of the code looks to be working as expected (WIFI integration and 'httpd service' work fine).
I use Raspberry Pi Pico W with latest MicroPython loaded.
Please advice... Thanks!
import machine
import _thread
import network
import socket
import utime
from machine import Pin
led = machine.Pin('LED', machine.Pin.OUT)
ssid = 'someSSID'
password = 'somePASSWORD'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
html = """<!DOCTYPE html>
<html>
<body>
<div id="humidity">100</div>
<div id="temperature">21</div>
</body>
</html>
"""
sLock = _thread.allocate_lock()
def CoreTask():
while True:
sLock.acquire()
print('LED...')
led.on()
utime.sleep(1)
led.off()
utime.sleep(1)
sLock.release()
_thread.start_new_thread(CoreTask, ())
while True:
sLock.acquire()
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
utime.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print( 'ip = ' + status[0] )
# Open socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
# Listen for connections
while True:
try:
cl, addr = s.accept()
print('client connected from', addr)
request = cl.recv(1024)
print(request)
request = str(request)
response = html
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()
except OSError as e:
cl.close()
print('connection closed')
sLock.release()
I'm also keen to know a solution, so far the best try I have got the onboard led working in seperate thread is the following simple code, every other more complicated try was failed.
I have only tested this with onboard LED, so if anyone may try if threading works on real GPIO? If it does, I think this is not an issue as most of time we send out "status blinks" on other LED in project not the onboard one.
import machine
import _thread
import time
def led():
led = machine.Pin('LED', machine.Pin.OUT)
while True:
led.on()
time.sleep(.5)
led.off()
time.sleep(.5)
def pnt():
i=0
while True:
i += 1
print(f"\rThis is the {i} cycle......", sep="", end="")
time.sleep(1)
if __name__ == "__main__":
th1 = _thread.start_new_thread(pnt, ())
#th2 = _thread.start_new_thread(led, ()) This line did not work
led()
I think someone said in a video that the threading is still in experiment and has problems on pico w, and they are working on it.
I also could not workout how to achieve same result with uasycncio, it looks like calling the LED to blink is not about programming but real physical movement, so cannot be "await". Can anyone show ma a correct way?
It's is such an important function to waiting for program (connection loop) while sending "status blinks"

Python code after sockets connection executed only once

What are the intentions of this program:
I want to send some commands from a client to a server using sockets, the server then send these command to an Arduino using serial. And another thing that I want the server to do in the future is that periodically sends other commands to the Arduino without getting any input from the client, so the sockets needs to be non-blocking or there needs to be another way to run the code separately from the sockets code.
The problem is that the part that is supposed to send the command to the Arduino only runs once.
What I have come up with after playing with the debugger in Pycharm, is that the problem is that the following line blocks after a connection has been established, and thus not allowing the rest of the code to be run.
conn, addr = s.accept()
Is this correct, or is there something else wrong?
I have tried to set the socket to non-blocking but when I do this I get an error.
"BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately"
I have some basic knowledge of C/C++ and C# and am new to Python.
server.py
import socket
import serial
import sys
from _thread import *
import threading
import queue
# command that the client sends are "ON" and "OFF"
class serialConnect:
comPort =' '
baudrate = 115200
myserial = serial.Serial('COM5', baudrate)
def serialstart(self):
# self.comPort = input('Comport: ')
try:
self.myserial.open()
except IOError:
print('Port is already open!')
def serialRead(self):
data = self.myserial.read(16)
data.decode('UTF-8')
return data
def serialWrite(self, data):
data += '\n' #the arduino needs a \n after each command.
databytes = data.encode('UTF-8')
self.myserial.write(databytes)
print('send data: ', databytes)
def threaded_client(conn, dataqueue):
data = {bytes}
conn.send(str.encode('welcome, type your info \n'))
while True:
data = conn.recv(2048)
if not data:
break
reply = 'server output: ' + data.decode('UTF-8')
dataqueue.put(data.decode('UTF-8'))
print("Items in queue: ",dataqueue.qsize())
#conn.sendall(str.encode(reply))
print("Recieved data in threaded_client: ", data.decode('UTF-8') + '\n')
conn.close()
def Main():
ser = serialConnect()
host = ''
port = 5555
dataRecieved = 'hello'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.setblocking(1) #when set to non-blocking error occurs : "BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately"
workQueue = queue.Queue(10)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(5)
print('waiting for a connection')
while True:
try:
conn, addr = s.accept() #once connection is established it blocks?
print('connected to: ' + addr[0] + ':' + str())
t = threading.Thread(target=threaded_client, args=(conn, workQueue))
t.daemon = True
t.start()
except:
e = sys.exc_info()
print('Error:', e)
# This section of code is only run once, doesn't matter if put inside try block or not. :(
dataRecieved = workQueue.get()
print('The recieved data: ', dataRecieved)
ser.serialstart()
ser.serialWrite(dataRecieved)
if __name__ == '__main__':
Main()
client.py
import socket
def Main():
host = '127.0.0.1'
port = 5555
message = "<,R,G,B,>"
mySocket = socket.socket()
mySocket.connect((host, port))
while message != 'q':
message = input(" -> ")
mySocket.send(message.encode())
mySocket.close()
if __name__ == '__main__':
Main()
Arduino Code
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
int LEDpin = 10;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(10, OUTPUT);
Serial.begin(19200);
}
// the loop function runs over and over again forever
void loop() {
serialEvent();
if(stringComplete){
Serial.println(inputString);
if(inputString == "ON\n"){
digitalWrite(LEDpin, HIGH); // turn the LED on (HIGH is the voltage level)
}
if(inputString == "OFF\n"){
digitalWrite(LEDpin, LOW); // turn the LED off by making the voltage LOW
}
inputString = "";
stringComplete = false;
}
}
void serialEvent()
{
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
Refactored server code for anyone that is interested in it.
I am not sure if this is up to standard, but it is working.
import serial
import socket
import queue
import sys
import threading
class serialConnect:
comPort = 'COM5'
baudrate = 115200
myserial = serial.Serial(comPort, baudrate)
def serial_run(self):
# self.comPort = input('Comport: ')
try:
if not self.myserial.isOpen():
self.myserial.open()
else:
print('Port is already open!')
except IOError as e:
print('Error: ', e)
def serial_read(self):
data = self.myserial.read(16)
data.decode('UTF-8')
return data
def serial_write(self, data):
data += '\n' #the arduino needs a \n after each command.
databytes = data.encode('UTF-8')
self.myserial.write(databytes)
print('send data: ', databytes)
class socketServer:
host = ''
port = 5555
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setblocking(1)
data_queue = queue.Queue(1)
def __init__(self):
try:
self.soc.bind((self.host, self.port))
except:
print('Bind error: ', sys.exc_info())
self.soc.listen(5)
def socket_accept_thread(self):
while True:
try:
print('Waiting for a new connection')
conn, addr = self.soc.accept()
client_thread = threading.Thread(target=self.threaded_client, args=(conn, self.data_queue))
client_thread.daemon = True
client_thread.start()
except:
print('Accept thread Error: ', sys.exc_info())
def threaded_client(self, conn, data_queue):
# conn.send(str.encode('welcome, type your info \n'))
try:
while True:
data = conn.recv(2048)
if not data:
break
# reply = 'server output: ' + data.decode('UTF-8')
data_queue.put(data.decode('UTF-8'))
print("Items in queue: ", data_queue.qsize())
# conn.sendall(str.encode(reply))
print("Received data in threaded_client: ", data.decode('UTF-8'))
except:
print("Error: ", sys.exc_info())
conn.close()
def get_data(self):
data = self.data_queue.get()
return data
def Main():
server = socketServer()
arduino_conn = serialConnect()
accept_thread = threading.Thread(target=server.socket_accept_thread)
data_received = 'Nothing received'
while True:
if not accept_thread.is_alive():
accept_thread.daemon = True
accept_thread.start()
arduino_conn.serial_run()
data_received = server.get_data()
arduino_conn.serial_write(data_received)
if __name__ == '__main__':
Main()

server doesn't send data to clients

I have this piece of code for server to handle clients. it properly receive data but when i want to send received data to clients nothing happens.
server
import socket
from _thread import *
class GameServer:
def __init__(self):
# Game parameters
board = [None] * 9
turn = 1
# TCP parameters specifying
self.tcp_ip = socket.gethostname()
self.tcp_port = 9999
self.buffer_size = 2048
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.s.bind((self.tcp_ip, self.tcp_port))
except:
print("socket error, Please try again! ")
self.s.listen(5)
print('Waiting for a connection...')
def messaging(self, conn):
while True:
data = conn.recv(self.buffer_size)
if not data:
break
print("This data from client:", data)
conn.send(data)
def thread_run(self):
while True:
conn, addr = self.s.accept()
print('connected to: ' + addr[0] + " : " + str(addr[1]))
start_new_thread(self.messaging, (conn,))
def main():
gameserver = GameServer()
gameserver.thread_run()
if __name__ == '__main__':
main()
'
I want to if data received completely send to clients by retrieve the address of sender and send it to other clients by means of conn.send() but seems there is no way to do this with 'send()' method.
The piece of client side code
'
def receive_parser(self):
global turn
rcv_data = self.s.recv(4096)
rcv_data.decode()
if rcv_data[:2] == 'c2':
message = rcv_data[2:]
if message[:3] == 'trn':
temp = message[3]
if temp == 2:
turn = -1
elif temp ==1:
turn = 1
elif message[:3] == 'num':
self.set_text(message[3])
elif message[:3] == 'txt':
self.plainTextEdit_4.appendPlainText('client1: ' + message[3:])
else:
print(rcv_data)
'
the receiver method does not receive any data.
I modified your code a little(as I have python 2.7) and conn.send() seems to work fine. You can also try conn.sendall(). Here is the code I ran:
Server code:
import socket
from thread import *
class GameServer:
def __init__(self):
# Game parameters
board = [None] * 9
turn = 1
# TCP parameters specifying
self.tcp_ip = "127.0.0.1"#socket.gethostname()
self.tcp_port = 9999
self.buffer_size = 2048
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.s.bind((self.tcp_ip, self.tcp_port))
except:
print("socket error, Please try again! ")
self.s.listen(5)
print('Waiting for a connection...')
def messaging(self, conn):
while True:
data = conn.recv(self.buffer_size)
if not data:
break
print("This data from client:", data)
conn.send(data)
def thread_run(self):
while True:
conn, addr = self.s.accept()
print('connected to: ' + addr[0] + " : " + str(addr[1]))
start_new_thread(self.messaging, (conn,))
def main():
gameserver = GameServer()
gameserver.thread_run()
main()
Client code:
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9999))
def receive_parser():
#global turn
s.sendall("hello world")
rcv_data = s.recv(4096)
# rcv_data.decode()
# if rcv_data[:2] == 'c2':
# message = rcv_data[2:]
# if message[:3] == 'trn':
# temp = message[3]
# if temp == 2:
# turn = -1
# elif temp ==1:
# turn = 1
# elif message[:3] == 'num':
# self.set_text(message[3])
# elif message[:3] == 'txt':
# self.plainTextEdit_4.appendPlainText('client1: ' + message[3:])
# else:
print(rcv_data)
receive_parser()