Answers for "send to and from from socket server and client"

2

tcp client using sockets in python

from socket import *
import sys
import json


serverName = ""
serverPort = 6100


clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))

sample_data = {
	"Aparna" : 1,
	"Pooja" : 2,
	"Shreya" : 3,
	"Tanishq" : 4
}

serialized_data = json.dumps(sample_data) #data serialized

# clientSocket.send(str.encode(sample_data))
clientSocket.send(str.encode(serialized_data))

response_data = clientSocket.recv(1024)
print("Response data from server : ", response_data.decode())

clientSocket.close()
Posted by: Guest on November-15-2020
0

send message from server to client python

# text_send_server.py

import socket
import select
import time

HOST = 'localhost'
PORT = 65439

ACK_TEXT = 'text_received'


def main():
    # instantiate a socket object
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('socket instantiated')

    # bind the socket
    sock.bind((HOST, PORT))
    print('socket binded')

    # start the socket listening
    sock.listen()
    print('socket now listening')

    # accept the socket response from the client, and get the connection object
    conn, addr = sock.accept()      # Note: execution waits here until the client calls sock.connect()
    print('socket accepted, got connection object')

    myCounter = 0
    while True:
        message = 'message ' + str(myCounter)
        print('sending: ' + message)
        sendTextViaSocket(message, conn)
        myCounter += 1
        time.sleep(1)
    # end while
# end function

def sendTextViaSocket(message, sock):
    # encode the text message
    encodedMessage = bytes(message, 'utf-8')

    # send the data via the socket to the server
    sock.sendall(encodedMessage)

    # receive acknowledgment from the server
    encodedAckText = sock.recv(1024)
    ackText = encodedAckText.decode('utf-8')

    # log if acknowledgment was successful
    if ackText == ACK_TEXT:
        print('server acknowledged reception of text')
    else:
        print('error: server has sent back ' + ackText)
    # end if
# end function

if __name__ == '__main__':
    main()
Posted by: Guest on November-18-2020

Code answers related to "send to and from from socket server and client"

Python Answers by Framework

Browse Popular Code Answers by Language