-
Sockets in python
Hey there guys, been looking into sockets in python recently but i'm having a little trouble getting my program to work rite.
It's just a random number generator game but I want to make it available over a network. So people can connect, play and then quit. I know how to open a socket then close it. I've done the basic examples in some tutorials but what I don't get(and i'm sure it's something stupid that i'm just not realising) is how to actually incorporate it into my program.
Code:
print "Hello, World!"
#I put "Hello World" into all of my programs. Just as a kind of good practise thing.
# Guessing Game
import random
# Start while loop
number = random.randrange(1,100)
guess = 0
while guess != number:
guess = int(raw_input("What is your guess? "))
if guess == number:
print "Well done you got it!"
elif guess < number:
print "Sorry it's higher than that"
elif guess > number:
print "Sorry it's lower than that"
else:
break
print
print "Thanks for playing random!"
That's the game. I'm sure it's pretty ugly code so if anyones got any suggestions on how to clean it up that would also be cool.
-
Here is the socket example I got from a tutorial
Code:
print "Hello, World!"
# A simple echo server
"""
A simple echo server
"""
import socket
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
client.send(data)
client.close()
-
Heh, I'm not a Python guy, but sockets are usually a general concept based around the Berkeley C implementation. In that essecene you generally would write to the socket as if though it were a file. See in C a socket descriptor is pretty much the same as a file descriptor except that you can only move through it sequentially and can't seek back and forth like you can through a file. Not sure how python handles files though so this could be totally different. **** maybe py treats a socket as a descriptor or maybe its a class. if it is a descriptor you should be able to write to it just like a file. If it is a class then see if socket has methods like write or send and read or recv. I'll try and get a glimpse at pythons socket implementation and point you better when I'm sober and such.
Page generated in 1,717,385,139.47695 seconds with 10 queries