Help with client/server socket with mathematical python sum interactions

Asked

Viewed 181 times

2

I am studying about socket and wanted to make a socket that when the client type 5 and another 5 the server responds 10 and returns to the client the answer. How I change my code to have this interaction?

** socket_server.py file

#!/usr/bin/env python

from socket import *
from time import time, ctime

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while 1:
print ("waiting for connection...")
tcpClisock, addr = tcpSerSock.accept()
print ("...connected from:"), addr

while 1:
data = tcpClisock.recv(BUFSIZ)
print ("[+] %s") % (data)
if data=="exit": 
exit
tcpClisock.send("[SERVER]vc digitou "+data) 

tcpClisock.close()
exit
tcpSerSock.close()

** socket_client.py file

#!/usr/bin/env python 

from socket import * 


HOST = 'localhost' 
PORT = 21567 
BUFSIZ = 1024 
ADDR = (HOST, PORT) 

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR) 

while 1: 
data = raw_input("CLIENT > ")
print ("[CLIENT] vc digitou %s") % (data) 
if not data: 
break
tcpCliSock.send(data) 
data = tcpCliSock.recv(1024) 

if not data: 
break 
print (data) 

tcpCliSock.close()

1 answer

0

You can declare a global variable on the server (socket_servidor.py) to serve as an accountant:

soma = 0
...
if data == "exit":
    exit
else
    soma += data
    print(soma)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.