1

I wrote two applictions which comunicate by socket. This is the code:

Server:

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("",9999))
server_socket.listen(5)

video = True
power = True

print "TCPServer Waiting for client on port 9999"

while 1:
    client_socket,address = server_socket.accept()
    print "I got a connection from ", address

    while 1:
        data = client_socket.recv(512)
        if data == 'vc' & video == True:
            data = 'You can connect to Video'
            video = False
            client_socket.send(data)
        elif data == 'pc' & power == True:
            data = 'You can connect to Power Switch'
            power = False
            client_socket.send(data)
        else :
            data = 'Device is in use - wait a few secconds'
            client_socket.send(data)

Client:

import socket
import time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 9999))
while 1:
    data = ( 'Please vc or pc: ' )
    time.sleep(5)
    if data=='pc' | data=='vc':
        print 'send to server: ' + data
        time.sleep(5)
        client_socket.send(data)
        data = client_socket.recv(512)
        print data
    else:
        print 'bad data - please try again'

    print data
    time.sleep(5)

I've just started my adventure with sockets and I have a problem. Why I don't see server response? I paste in code time.sleep() to stop the program and see rosponses, but those applications terminate after I wrote first message in client terminal and press enter. Please, help me.

I work on Windows 32bit. Python 2.6

1 Answer 1

2

You don't send anything. I presume the line data = "Please vc or pc: is meant to get input from the user, but it just assigns the string to data. Then when you check if data == 'pc' | data == 'vc' the check fails so it prints "bad data".

Also do not use | in boolean expressions - use or and and. | and & will do bitwise manipulation - sometimes that will do the right thing, but other times it will bite you in the butt.

Sign up to request clarification or add additional context in comments.

1 Comment

I've just fixed my problem before your answer. I will edit main post ;) Thanx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.