1

I am new to Python and would appreciate some help. My server receives any kind of data from the client. How can I modify the server code such that when it receives a certain string of text it responds with a particular string of text?

E.g. Client sends *101# and Server responds with Hello World

but if the client sends *102# Server would respond with Sorry

Thanks Graham

Server

from socket import *

serverHost=''
serverport=50007

#open socket to listen 

sSock = socket(AF_INET,SOCK_STREAM)
sSock.bind((serverHost,serverport))
sSock.listen(3)

#handle connection
while 1:
    conn,addr = sSock.accept()
    print ('Client Connection:', addr)
    while 1:
        data = conn.recv(1024)
        if not data: break
        print (' Server Received:', data)
        newData = data.replace('Client','Processed')
        conn.send(newData)

conn.close()

Client

import sys
from socket import  *

serverHost = 'localhost'
serverPort = 50007

message = ['*325#']

if len(sys.argv) > 1:
    serverHost = sys.argv[1]

#create my socket
sSock = socket(AF_INET, SOCK_STREAM)


#connect to server 
sSock.connect((serverHost, serverPort))


#send a message
for item in message:
    sSock.send(item)
    data = sSock.recv(1024)
    print ('Client received: ', 'data')

sSock.close()

1 Answer 1

1

Well, just take:

newData = data.replace('Client','Processed')

and replace it with something like:

if data == '*101#':
    newData = 'Hello World'
elif data == '*102#':
    newData = 'Sorry'
else:
    newData = data.replace('Client','Processed')

Not that this is optimal, but it should get you started.

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

Comments

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.