This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#76 2011-12-22 18:58:48

gbear605
Scratcher
Registered: 2008-03-06
Posts: 1000+

Re: Chat.PY and Other Features

Magnie wrote:

gbear605 wrote:

BTW, you should make it so the mirror doesn't say that there are no errors, it should only says if there are errors XD

Yeah, that was meant for debugging.  tongue

Also, post the source for the server.


Yeah, I'm mostly inactive.  I check in once in a while though.  If you want to contact me, I have a contact form at my website, http://escratch.org

Offline

 

#77 2011-12-22 19:02:09

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

gbear605 wrote:

Magnie wrote:

gbear605 wrote:

BTW, you should make it so the mirror doesn't say that there are no errors, it should only says if there are errors XD

Yeah, that was meant for debugging.  tongue

Also, post the source for the server.

On the first post now.

Offline

 

#78 2011-12-22 19:08:32

gbear605
Scratcher
Registered: 2008-03-06
Posts: 1000+

Re: Chat.PY and Other Features

big_smile 

Last edited by gbear605 (2011-12-22 19:08:41)


Yeah, I'm mostly inactive.  I check in once in a while though.  If you want to contact me, I have a contact form at my website, http://escratch.org

Offline

 

#79 2011-12-22 19:21:42

JJROCKER
Scratcher
Registered: 2010-09-06
Posts: 1000+

Re: Chat.PY and Other Features

Is this completely safe?


http://www.blocks.scratchr.org/API.php?action=random&return=image&link1=http://img255.imageshack.us/img255/3491/signature1y.jpg&link2=http://img577.imageshack.us/img577/5272/signature1sx.jpg&link3=http://img4.imageshack.us/img4/8514/signature1et.jpg&link4=http://i.imgur.com/POEpQyZ.png&link5=http://img163.imageshack.us/img163/4640/jjrockerfinal.jpg

Offline

 

#80 2011-12-22 19:22:55

gbear605
Scratcher
Registered: 2008-03-06
Posts: 1000+

Re: Chat.PY and Other Features

JJROCKER wrote:

Is this completely safe?

Yes


Yeah, I'm mostly inactive.  I check in once in a while though.  If you want to contact me, I have a contact form at my website, http://escratch.org

Offline

 

#81 2011-12-22 19:23:19

Solarbuddy
Scratcher
Registered: 2009-04-14
Posts: 500+

Re: Chat.PY and Other Features

JJROCKER wrote:

Is this completely safe?

Yep!
That's 2 that say it is.  smile


http://bit.ly/Vn3zid
                  View my latest project

Offline

 

#82 2011-12-22 19:26:31

JJROCKER
Scratcher
Registered: 2010-09-06
Posts: 1000+

Re: Chat.PY and Other Features

How do I extract the folder?


http://www.blocks.scratchr.org/API.php?action=random&return=image&link1=http://img255.imageshack.us/img255/3491/signature1y.jpg&link2=http://img577.imageshack.us/img577/5272/signature1sx.jpg&link3=http://img4.imageshack.us/img4/8514/signature1et.jpg&link4=http://i.imgur.com/POEpQyZ.png&link5=http://img163.imageshack.us/img163/4640/jjrockerfinal.jpg

Offline

 

#83 2011-12-22 19:28:46

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

JJROCKER wrote:

How do I extract the folder?

Right-click the .zip and find something called "extract" or "zip" in the list. Common-sense.

Offline

 

#84 2011-12-22 19:42:47

JJROCKER
Scratcher
Registered: 2010-09-06
Posts: 1000+

Re: Chat.PY and Other Features

Magnie wrote:

JJROCKER wrote:

How do I extract the folder?

Right-click the .zip and find something called "extract" or "zip" in the list. Common-sense.

I'm so confused. Am I supposed to have it open when I do this?

Last edited by JJROCKER (2011-12-22 19:42:58)


http://www.blocks.scratchr.org/API.php?action=random&return=image&link1=http://img255.imageshack.us/img255/3491/signature1y.jpg&link2=http://img577.imageshack.us/img577/5272/signature1sx.jpg&link3=http://img4.imageshack.us/img4/8514/signature1et.jpg&link4=http://i.imgur.com/POEpQyZ.png&link5=http://img163.imageshack.us/img163/4640/jjrockerfinal.jpg

Offline

 

#85 2011-12-22 20:00:40

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

JJROCKER wrote:

Magnie wrote:

JJROCKER wrote:

How do I extract the folder?

Right-click the .zip and find something called "extract" or "zip" in the list. Common-sense.

I'm so confused. Am I supposed to have it open when I do this?

Just go through all the instructions listed ( ignore the "get this block" parts ).

Offline

 

#86 2011-12-22 20:19:46

Solarbuddy
Scratcher
Registered: 2009-04-14
Posts: 500+

Re: Chat.PY and Other Features

I'm making a tutorial video now.  smile
Hopefully it will help some people.  big_smile


http://bit.ly/Vn3zid
                  View my latest project

Offline

 

#87 2011-12-22 20:27:12

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

Solarbuddy wrote:

I'm making a tutorial video now.  smile
Hopefully it will help some people.  big_smile

I will put it on the first post.  big_smile

Get on chat!

Offline

 

#88 2011-12-22 20:45:38

Tbtemplex97
Scratcher
Registered: 2011-11-12
Posts: 100+

Re: Chat.PY and Other Features

It Works!


Online Status: http://blocks.scratchr.org/API.php?action=onlineStatus&user=Tbtemplex97
Darkspace Coming Soon!, Try the Singleplayer Demo

Offline

 

#89 2011-12-22 21:36:59

Tbtemplex97
Scratcher
Registered: 2011-11-12
Posts: 100+

Re: Chat.PY and Other Features

I have made a tutorial Click Here


Online Status: http://blocks.scratchr.org/API.php?action=onlineStatus&user=Tbtemplex97
Darkspace Coming Soon!, Try the Singleplayer Demo

Offline

 

#90 2011-12-22 21:42:30

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

Tbtemplex97 wrote:

I have made a tutorial Click Here

Thanks very much!

Offline

 

#91 2011-12-22 22:16:18

flashgocrazy
Scratcher
Registered: 2011-01-12
Posts: 500+

Re: Chat.PY and Other Features

Magnie wrote:

Okay, so I would like to test my Scratch Live Clone that I made in Python. To simplify the process of connecting to the server through a Python mirror, I have converted the mirror into a .exe and I would like someone to test two things for me. 1) See if it works, 2) if you can connect to my server.  smile

http://www.scratch.mit.edu/ext/youtube/?v=SZHHjahLbfg <- Tutorial buy Tbtemplex97. Thanks!

Scratch Mirror: http://kabam.herobo.com/ScratchMirror.zip
Source:

Code:

# Scratch Mirror
# Version 1.5.0
# By: Magnie

import socket # Network base
import time # For delaying purposes mostly.
import threading # So it can send and receive at the same time anytime.

# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# CHOST is the IP Scratch is running on, if you are running it    #
# on this computer, then the IP is 127.0.0.1                      #
# Theoretically you could run this Mirror on another computer.    #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# CPOST is the port Scratch is listening on, the default is       #
# 42001. Usually this is only change by a Scratcher who knows a   #
# about Squeak and networking with sockets.                       #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
CHOST = '127.0.0.1'
CPORT = 42001

# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# SHOST is the IP the server is running on.                       #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# SPORT is the port that the server is using. 42002 is the        #
# unofficial port for Scratch Servers. The host will need to make #
# sure to port-forward the port so people can connect from the    #
# internet.                                                       #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
SHOST = raw_input("Server IP: ")
SPORT = int( raw_input("Server Port: ") )

# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# Some extra settings that are more for advanced users are below. #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #

# Time between checking the threads for broken ones.
THREADCHECK = 5



class Client(threading.Thread): # This class listens for messages sent from Scratch and sends it to the Server.
    def __init__(self, CHOST, CPORT):
        threading.Thread.__init__(self) # Initialize it, basically just separate it from the main thread.
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Defines the type of connection ( UPD, TCP on IPv4 or IPv6 )
        print("Connecting to Scratch...")
        self.sock.connect((CHOST, CPORT)) # Connect to Scratch
        print("Connected to Scratch!")
        
        self.alive = 1
        
    def run(self):
        global running
        print "Listening for Scratch messages."
        while running:
            try:
                data = self.sock.recv(1024) # Listens for messages sent from Scratch.
                self.send(data)
            except:
                self.alive = 0
    
    def send(self, message):
        server.sock.send(message) # Send the data to the server.
    
    def disconnect(self):
        self.sock.close()

class Server(threading.Thread): # This class listens for messages from the Server and sends it to Scratch.
    def __init__(self, SHOST, SPORT):
        threading.Thread.__init__(self) # Initialize it, basically just separate it from the main thread.
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Defines the type of connection ( UPD, TCP on IPv4 or IPv6 )
        print("Connecting to Scratch Server...")
        self.sock.connect((SHOST, SPORT)) # Connect to the Server.
        print("Connected to Server!")
        
        self.alive = 1
        
    def run(self):   
        global running
        print "Listening for Server messages."
        while running:
            try:
                data = self.sock.recv(1024) # Listens for messages sent from the Server.
                self.send(data)
            except:
                self.alive = 0
    
    def send(self, message):
        scratch.sock.send(message) # Sends messages to Scratch.
    
    def disconnect(self):
        self.sock.close()


running = 1
server = Server(SHOST, SPORT) # Start up the class for Server
server.start() # This starts the 'run' function on the class as well.

scratch = Client(CHOST, CPORT) # Start up the class for Scratch
scratch.start() # This starts the 'run' function.

while running:
    time.sleep(THREADCHECK) # The longer the wait time, the less CPU is used I think.
    if scratch.alive != 1: running = 0
    if server.alive != 1: running = 0
    
    if running == 0:
        running = 0
        server.disconnect() # Tell the server thread to disconnect
        scratch.disconnect() # Tell the scratch thread to disconnect

        server.join() # End the server thread.
        scratch.join() # End the scratch thread.
        print 'Error Check: Yes.'
    else: print 'Error Check: No errors.'
print "Finished running."

How To Setup:
1. Download the .zip

2. Extract it, the folder inside is called 'dist'

3. Open up the folder, you will notice a ScratchMirror.exe, don't run it yet.

4. Open up Scratch

5. In Scratch, get the broadcast block out and set the broadcast to "<var [enter random number here]"
OR
Download: http://scratch.mit.edu/projects/Magnie/2234885 and use that instead.

6. In Scratch, open up the Sensors tab and get the Sensor Value block.

7. Right-Click the Sensor Value block and click "enable remote connections"

8. Once that is enabled, go back to the 'dist' folder ( do not close Scratch ) and run the ScratchMirror.exe program

9. Server IP: scratch.playfultest.tk Server Port: 6112
If that doesn't work, try 174.27.218.81

10. You should get something like this: ( 127.0.0.1 is not the IP you connect to, it's scratch.playfultest.tk )

Code:

Server IP: 127.0.0.1
Server Port: 6112
Connecting to Scratch...
Connected to Scratch!
Listening for Scratch messages.
 Connecting to Scratch Server...
Connected to Server!
Listening for Server messages.

If you get that, then you have successfully connected! If you don't get that, then please paste the text here so I can debug. ( Right-Click the title, click 'Edit' then 'Mark', select the area you want to copy then right-click again and the highlighted text should disappear, you have now copied it. )

11. Once you are connected, bring up Scratch again and click the broadcast block so it "glows" white ( indicating it is running )
OR
Run the Chat Program

12. Click the drop-down menu on the Sensor Value block and you should see 'var' at the bottom. Select 'var' then click the block once and it should display the random text you entered into the broadcast.
OR
Ignore this

You can do it with any variable name ( except spaces ) and set it to pretty much anything. Now since other people may update it, you can use ">var" to get the update. Or if you want, you can use "^var" to "follow" the variable so it automatically updates.

Set a Variable: <[var] [value]
Get a Variable: >[var]
Follow a Variable: ^[var]

There is a broadcast that is sent called "^follow_update" if you are following a variable. So if you set up a script to receive the ^follow_update broadcast, you can have it run that script.

Code:

Server Source:
# Scratch Server
# Version 1.0.0
# By: Magnie

import threading
import socket
import sys
from array import array

class Server: 
    def __init__(self): 

        # Server Information
        self.host = '' # Game host
        self.port = int( raw_input("Host Port: ") ) # Game port
        self.backlog = 5 # Maximum clients?
        self.size = 1024 # Maximum receive size
        self.server = None 
        self.threads = [] # Client threads ( just a record )
        self.variables = {} # user : value

        # Game Information

    def open_socket(self): 
        try: # Try settings up the connection
            self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Define socket type
            self.server.bind((self.host,self.port)) # Bind server to port
            self.server.listen( self.backlog ) # Wait for clients to connect
        except socket.error, (value,message): # If it can't connect Then print out the error and shut down the server.
            if self.server: 
                self.server.close() 
            print "Could not open socket: " + message 
            sys.exit(1)

    def run(self):
        self.open_socket()
        running = 1
        id = 0 # To define each client.
        while running:
            id += 1 # Increase so no client has the same ID.
            c = Client(self.server.accept()) # Waits for a client then accepts it.
            c.start() # Starts it.
            self.threads.append(c) # Adds it to a list so the variable c and be used for the next client.

        # Disconnect all clients.
        self.server.close() # Disconnect socket.
        for c in self.threads: # For each thread
            c.join() # End that thread.

class Client(threading.Thread): 
    def __init__(self,(client,address)): 
        threading.Thread.__init__(self) 
        self.client = client 
        self.address = address 
        self.size = 1024 
        self.follow = []
        
        self.alive = 1
        
        print self.address, 'has connected.'

    def run(self): 
        self.running = 1 
        while self.running:

            data = self.client.recv(self.size) # Wait for data.
            data = parseScratchCommand(data) # Parse the data.
            print self.address[0], ":", data
            
            if data[0] == 'ping':
                self.client.send("Pong")
                print self.address[0], 'sent a ping.'
            
            if data[0] == 'sensor-update': # If a variable is updated
                
                #print data[1:]
                continue

            elif data[0] == 'broadcast': # If a broadcast is sent
                
                data[1] = data[1][1:]
                data[-1] = data[-1][:-1]
                
                if data[1] == '': continue
                
                if data[1][0] == '<' or data[1][0] == '>':
                    if data[1][1:] not in s.variables:
                        s.variables[ data[1][1:] ] = ""
                        
                if data[1][0] == '>':
                    vari = data[1][1:]
                    value = s.variables[ vari ]
                    self.client.send( sendScratchCommand('sensor-update "'+vari+'" "'+value+'"') )
                    
                    for follow in s.threads:
                        follow.follow_update(vari)
                    
                    print self.address[0], "retrevied variable ", vari,"."
                    
                elif data[1][0] == '<':
                    vari = data[1][1:]
                    value = ' '.join( data[2:] )
                    s.variables[ vari ] = value
                    self.client.send( sendScratchCommand('sensor-update "'+vari+'" "'+value+'"') )
                    
                    for follow in s.threads:
                        follow.follow_update(vari)
                    
                    print self.address
                    print vari,"=",value
                    
                elif data[1][0] == '^':
                    vari = data[1][1:]
                    self.follow.append( vari )
                    
                    print self.address, "has followed", vari,"."
                    
                else:
                    continue
            
            else: 
                self.client.close() # Close the connection.
                print self.address, 'has closed the connection.' # Debugging purposes and just informative if you are watching it.
                self.running = 0 
                self.alive = 0
                
    def follow_update(self, vari):
        if vari in self.follow and self.alive == 1:
            value = s.variables[ vari ]
            try:
                self.client.send( sendScratchCommand('sensor-update "'+vari+'" "'+value+'"') )
                self.client.send( sendScratchCommand('broadcast "^follow_update"') )
            except:
                print '--Dead Thread--'
                self.running = 0
                self.alive = 0
                self.join()
            
def parseScratchCommand(cmd):
    cmd = cmd[4:] # Remove the first four letters ( it's annoying to deal with )
    cmd = cmd.split(' ') # Split the string where there is a space. It helps to find out broadcasts.
    return cmd # Return the list. ['broadcast/sensor-update', 'valueWord1', 'valueWord2']

def sendScratchCommand(cmd): # I was never sure what this did, but it's required.
    n = len(cmd)
    a = array('c')
    a.append(chr((n >> 24) & 0xFF))
    a.append(chr((n >> 16) & 0xFF))
    a.append(chr((n >>  8) & 0xFF))
    a.append(chr(n & 0xFF))
    return (a.tostring() + cmd)

if __name__ == "__main__":
    s = Server() 
    s.run()

Any thoughts?

how do you set this up on x10hosting.com?


◕‿◕

Offline

 

#92 2011-12-22 22:28:03

Tbtemplex97
Scratcher
Registered: 2011-11-12
Posts: 100+

Re: Chat.PY and Other Features

flashgocrazy wrote:

Magnie wrote:

Okay, so I would like to test my Scratch Live Clone that I made in Python. To simplify the process of connecting to the server through a Python mirror, I have converted the mirror into a .exe and I would like someone to test two things for me. 1) See if it works, 2) if you can connect to my server.  smile

http://www.scratch.mit.edu/ext/youtube/?v=SZHHjahLbfg <- Tutorial buy Tbtemplex97. Thanks!

Scratch Mirror: http://kabam.herobo.com/ScratchMirror.zip
Source:

Code:

# Scratch Mirror
# Version 1.5.0
# By: Magnie

import socket # Network base
import time # For delaying purposes mostly.
import threading # So it can send and receive at the same time anytime.

# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# CHOST is the IP Scratch is running on, if you are running it    #
# on this computer, then the IP is 127.0.0.1                      #
# Theoretically you could run this Mirror on another computer.    #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# CPOST is the port Scratch is listening on, the default is       #
# 42001. Usually this is only change by a Scratcher who knows a   #
# about Squeak and networking with sockets.                       #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
CHOST = '127.0.0.1'
CPORT = 42001

# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# SHOST is the IP the server is running on.                       #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# SPORT is the port that the server is using. 42002 is the        #
# unofficial port for Scratch Servers. The host will need to make #
# sure to port-forward the port so people can connect from the    #
# internet.                                                       #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
SHOST = raw_input("Server IP: ")
SPORT = int( raw_input("Server Port: ") )

# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
# Some extra settings that are more for advanced users are below. #
# ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #

# Time between checking the threads for broken ones.
THREADCHECK = 5



class Client(threading.Thread): # This class listens for messages sent from Scratch and sends it to the Server.
    def __init__(self, CHOST, CPORT):
        threading.Thread.__init__(self) # Initialize it, basically just separate it from the main thread.
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Defines the type of connection ( UPD, TCP on IPv4 or IPv6 )
        print("Connecting to Scratch...")
        self.sock.connect((CHOST, CPORT)) # Connect to Scratch
        print("Connected to Scratch!")
        
        self.alive = 1
        
    def run(self):
        global running
        print "Listening for Scratch messages."
        while running:
            try:
                data = self.sock.recv(1024) # Listens for messages sent from Scratch.
                self.send(data)
            except:
                self.alive = 0
    
    def send(self, message):
        server.sock.send(message) # Send the data to the server.
    
    def disconnect(self):
        self.sock.close()

class Server(threading.Thread): # This class listens for messages from the Server and sends it to Scratch.
    def __init__(self, SHOST, SPORT):
        threading.Thread.__init__(self) # Initialize it, basically just separate it from the main thread.
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Defines the type of connection ( UPD, TCP on IPv4 or IPv6 )
        print("Connecting to Scratch Server...")
        self.sock.connect((SHOST, SPORT)) # Connect to the Server.
        print("Connected to Server!")
        
        self.alive = 1
        
    def run(self):   
        global running
        print "Listening for Server messages."
        while running:
            try:
                data = self.sock.recv(1024) # Listens for messages sent from the Server.
                self.send(data)
            except:
                self.alive = 0
    
    def send(self, message):
        scratch.sock.send(message) # Sends messages to Scratch.
    
    def disconnect(self):
        self.sock.close()


running = 1
server = Server(SHOST, SPORT) # Start up the class for Server
server.start() # This starts the 'run' function on the class as well.

scratch = Client(CHOST, CPORT) # Start up the class for Scratch
scratch.start() # This starts the 'run' function.

while running:
    time.sleep(THREADCHECK) # The longer the wait time, the less CPU is used I think.
    if scratch.alive != 1: running = 0
    if server.alive != 1: running = 0
    
    if running == 0:
        running = 0
        server.disconnect() # Tell the server thread to disconnect
        scratch.disconnect() # Tell the scratch thread to disconnect

        server.join() # End the server thread.
        scratch.join() # End the scratch thread.
        print 'Error Check: Yes.'
    else: print 'Error Check: No errors.'
print "Finished running."

How To Setup:
1. Download the .zip

2. Extract it, the folder inside is called 'dist'

3. Open up the folder, you will notice a ScratchMirror.exe, don't run it yet.

4. Open up Scratch

5. In Scratch, get the broadcast block out and set the broadcast to "<var [enter random number here]"
OR
Download: http://scratch.mit.edu/projects/Magnie/2234885 and use that instead.

6. In Scratch, open up the Sensors tab and get the Sensor Value block.

7. Right-Click the Sensor Value block and click "enable remote connections"

8. Once that is enabled, go back to the 'dist' folder ( do not close Scratch ) and run the ScratchMirror.exe program

9. Server IP: scratch.playfultest.tk Server Port: 6112
If that doesn't work, try 174.27.218.81

10. You should get something like this: ( 127.0.0.1 is not the IP you connect to, it's scratch.playfultest.tk )

Code:

Server IP: 127.0.0.1
Server Port: 6112
Connecting to Scratch...
Connected to Scratch!
Listening for Scratch messages.
 Connecting to Scratch Server...
Connected to Server!
Listening for Server messages.

If you get that, then you have successfully connected! If you don't get that, then please paste the text here so I can debug. ( Right-Click the title, click 'Edit' then 'Mark', select the area you want to copy then right-click again and the highlighted text should disappear, you have now copied it. )

11. Once you are connected, bring up Scratch again and click the broadcast block so it "glows" white ( indicating it is running )
OR
Run the Chat Program

12. Click the drop-down menu on the Sensor Value block and you should see 'var' at the bottom. Select 'var' then click the block once and it should display the random text you entered into the broadcast.
OR
Ignore this

You can do it with any variable name ( except spaces ) and set it to pretty much anything. Now since other people may update it, you can use ">var" to get the update. Or if you want, you can use "^var" to "follow" the variable so it automatically updates.

Set a Variable: <[var] [value]
Get a Variable: >[var]
Follow a Variable: ^[var]

There is a broadcast that is sent called "^follow_update" if you are following a variable. So if you set up a script to receive the ^follow_update broadcast, you can have it run that script.

Code:

Server Source:
# Scratch Server
# Version 1.0.0
# By: Magnie

import threading
import socket
import sys
from array import array

class Server: 
    def __init__(self): 

        # Server Information
        self.host = '' # Game host
        self.port = int( raw_input("Host Port: ") ) # Game port
        self.backlog = 5 # Maximum clients?
        self.size = 1024 # Maximum receive size
        self.server = None 
        self.threads = [] # Client threads ( just a record )
        self.variables = {} # user : value

        # Game Information

    def open_socket(self): 
        try: # Try settings up the connection
            self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Define socket type
            self.server.bind((self.host,self.port)) # Bind server to port
            self.server.listen( self.backlog ) # Wait for clients to connect
        except socket.error, (value,message): # If it can't connect Then print out the error and shut down the server.
            if self.server: 
                self.server.close() 
            print "Could not open socket: " + message 
            sys.exit(1)

    def run(self):
        self.open_socket()
        running = 1
        id = 0 # To define each client.
        while running:
            id += 1 # Increase so no client has the same ID.
            c = Client(self.server.accept()) # Waits for a client then accepts it.
            c.start() # Starts it.
            self.threads.append(c) # Adds it to a list so the variable c and be used for the next client.

        # Disconnect all clients.
        self.server.close() # Disconnect socket.
        for c in self.threads: # For each thread
            c.join() # End that thread.

class Client(threading.Thread): 
    def __init__(self,(client,address)): 
        threading.Thread.__init__(self) 
        self.client = client 
        self.address = address 
        self.size = 1024 
        self.follow = []
        
        self.alive = 1
        
        print self.address, 'has connected.'

    def run(self): 
        self.running = 1 
        while self.running:

            data = self.client.recv(self.size) # Wait for data.
            data = parseScratchCommand(data) # Parse the data.
            print self.address[0], ":", data
            
            if data[0] == 'ping':
                self.client.send("Pong")
                print self.address[0], 'sent a ping.'
            
            if data[0] == 'sensor-update': # If a variable is updated
                
                #print data[1:]
                continue

            elif data[0] == 'broadcast': # If a broadcast is sent
                
                data[1] = data[1][1:]
                data[-1] = data[-1][:-1]
                
                if data[1] == '': continue
                
                if data[1][0] == '<' or data[1][0] == '>':
                    if data[1][1:] not in s.variables:
                        s.variables[ data[1][1:] ] = ""
                        
                if data[1][0] == '>':
                    vari = data[1][1:]
                    value = s.variables[ vari ]
                    self.client.send( sendScratchCommand('sensor-update "'+vari+'" "'+value+'"') )
                    
                    for follow in s.threads:
                        follow.follow_update(vari)
                    
                    print self.address[0], "retrevied variable ", vari,"."
                    
                elif data[1][0] == '<':
                    vari = data[1][1:]
                    value = ' '.join( data[2:] )
                    s.variables[ vari ] = value
                    self.client.send( sendScratchCommand('sensor-update "'+vari+'" "'+value+'"') )
                    
                    for follow in s.threads:
                        follow.follow_update(vari)
                    
                    print self.address
                    print vari,"=",value
                    
                elif data[1][0] == '^':
                    vari = data[1][1:]
                    self.follow.append( vari )
                    
                    print self.address, "has followed", vari,"."
                    
                else:
                    continue
            
            else: 
                self.client.close() # Close the connection.
                print self.address, 'has closed the connection.' # Debugging purposes and just informative if you are watching it.
                self.running = 0 
                self.alive = 0
                
    def follow_update(self, vari):
        if vari in self.follow and self.alive == 1:
            value = s.variables[ vari ]
            try:
                self.client.send( sendScratchCommand('sensor-update "'+vari+'" "'+value+'"') )
                self.client.send( sendScratchCommand('broadcast "^follow_update"') )
            except:
                print '--Dead Thread--'
                self.running = 0
                self.alive = 0
                self.join()
            
def parseScratchCommand(cmd):
    cmd = cmd[4:] # Remove the first four letters ( it's annoying to deal with )
    cmd = cmd.split(' ') # Split the string where there is a space. It helps to find out broadcasts.
    return cmd # Return the list. ['broadcast/sensor-update', 'valueWord1', 'valueWord2']

def sendScratchCommand(cmd): # I was never sure what this did, but it's required.
    n = len(cmd)
    a = array('c')
    a.append(chr((n >> 24) & 0xFF))
    a.append(chr((n >> 16) & 0xFF))
    a.append(chr((n >>  8) & 0xFF))
    a.append(chr(n & 0xFF))
    return (a.tostring() + cmd)

if __name__ == "__main__":
    s = Server() 
    s.run()

Any thoughts?

how do you set this up on x10hosting.com?

i dont think u can


Online Status: http://blocks.scratchr.org/API.php?action=onlineStatus&amp;user=Tbtemplex97
Darkspace Coming Soon!, Try the Singleplayer Demo

Offline

 

#93 2011-12-22 22:30:11

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

flashgocrazy wrote:

how do you set this up on x10hosting.com?

You can't. This can't be setup on a webhost/website. It can only be setup on computers and servers ( not web-servers ).

Offline

 

#94 2011-12-22 22:38:24

Tbtemplex97
Scratcher
Registered: 2011-11-12
Posts: 100+

Re: Chat.PY and Other Features

Is the server up? it wont connect me?


Online Status: http://blocks.scratchr.org/API.php?action=onlineStatus&amp;user=Tbtemplex97
Darkspace Coming Soon!, Try the Singleplayer Demo

Offline

 

#95 2011-12-22 23:05:41

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

Tbtemplex97 wrote:

Is the server up? it wont connect me?

It's up, you just aren't pressing the green flag. Cause I see you connect.

Offline

 

#96 2011-12-23 05:42:31

roijac
Scratcher
Registered: 2010-01-19
Posts: 1000+

Re: Chat.PY and Other Features

tutorial buytongue

nobody have been on, i think, so i couldn't check much :S

Last edited by roijac (2011-12-23 06:31:45)

Offline

 

#97 2011-12-23 09:25:04

flashgocrazy
Scratcher
Registered: 2011-01-12
Posts: 500+

Re: Chat.PY and Other Features

Magnie wrote:

flashgocrazy wrote:

how do you set this up on x10hosting.com?

You can't. This can't be setup on a webhost/website. It can only be setup on computers and servers ( not web-servers ).

well, then how do you set it up on a server online?


◕‿◕

Offline

 

#98 2011-12-23 10:12:39

Tbtemplex97
Scratcher
Registered: 2011-11-12
Posts: 100+

Re: Chat.PY and Other Features

you need to buy a Dedicated server and use Virtual Desktop Connection, From there u download the Host's Command Prompt, then when someone goes to come online, they enter the ip of ur server and you will be the host.


Online Status: http://blocks.scratchr.org/API.php?action=onlineStatus&amp;user=Tbtemplex97
Darkspace Coming Soon!, Try the Singleplayer Demo

Offline

 

#99 2011-12-23 10:30:22

flashgocrazy
Scratcher
Registered: 2011-01-12
Posts: 500+

Re: Chat.PY and Other Features

Tbtemplex97 wrote:

you need to buy a Dedicated server and use Virtual Desktop Connection, From there u download the Host's Command Prompt, then when someone goes to come online, they enter the ip of ur server and you will be the host.

cant you just set up a website and search for ports using this?

Last edited by flashgocrazy (2011-12-23 15:16:18)


◕‿◕

Offline

 

#100 2011-12-23 11:12:15

Magnie
Scratcher
Registered: 2007-12-12
Posts: 1000+

Re: Chat.PY and Other Features

roijac wrote:

tutorial buytongue

nobody have been on, i think, so i couldn't check much :S

You were on while I was asleep.  tongue  I saw you connect and post a few messages.

But sending a message in general means that it works. Cause it only displays if you are connected to the server.

Tbtemplex97: What people normally do, is get a dedicated server ( or VPS , Virtual Private Server ) and SSH to it and type in commands through a console.

Flashgocrazy: No you can't, because webhosts are for websites, they can't really host applications. Most applications on websites ( like addicting games ) are on the client's browser. Webhosts don't have any open ports ( except for things like 22 and 21 FTP and possibly 23 Telnet, and if they provide it, whatever server email uses ).

Please realize that webhosts are for websites, not for anything else. If you want to host a server like what I am doing, you either have to use your own computer, or find a server. And servers are just text and terminals/consoles. Everything that happens on a server or computer is really just text ( or if you are really technical, binary ), all you are seeing on your screen is the computer telling the screen to display dots here and there. Since there isn't a screen for a server, you have to make one for yourself, and to communicate to the server, you use the terminal with SSH or another program.

MMOs only have text for the server. That's all it does.

Offline

 

Board footer