예제 #1
0
     )
     print(
         "Exit                 [End connection                                         ]\n"
     )
 # If input is less than 2 e.g simply "query" which is unclear
 # Structure of query timestamp of block 5: query timestamp 5
 elif user_input[0].lower() == "query" and len(user_input) >= 2:
     second_input = user_input[1]
     if second_input == "timestamp" and len(user_input) == 3:
         valid_input_flag = True
         sock.sendall(user_action.encode())
 # Structure of add command: add I am new block
 elif user_input[0].lower() == "add":
     valid_input_flag = True
     data_string = user_action[3:]
     add_flag = block_chain.addblock(data=data_string)
     # if successfully added to blockchain, send out the new block
     if add_flag is True:
         data_to_send = pickle.dumps(block_chain.getlatest())
         # Send client command to server
         sock.sendall(b"add block")
         # Send json string of new block
         sock.sendall(data_to_send)
 if exit_flag:
     break
 if valid_input_flag is False:
     print("Invalid Action!")
 elif list_flag is False:
     # Commands received should not be able to exceed 100 bytes
     # For this project assume block chain is small: within 256kb
     received_string = sock.recv(100).decode()
예제 #2
0
import socket
import sys
from blockchain import BlockChain
import pickle
import threading

# Create a TCP/IP Socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
blockchain = BlockChain()
blockchain.addblock("Assignment 2")
max_buffer_size = 256000  # kernel receive buffer size of socket
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)

# Thread handle for new TCP Connection
def handle_connection(connection, client_address):
    try:
        print('connection from', client_address)
        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(256)
            print('received {!r}'.format(data))
            if b"query latest" in data:
                data_to_send = pickle.dumps(blockchain.getlatest())  # Convert latest block to json string and send
                connection.sendall(b"send latest")
                connection.sendall(data_to_send)
            if b"query all" in data: