connect to socket server python code example

Example 1: python socket server

import socket

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('', 15555))

while True:
        socket.listen(5)
        client, address = socket.accept()
        print "{} connected".format( address )

        response = client.recv(255)
        if response != "":
                print response

print "Close"
client.close()
stock.close()

Example 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()

Example 3: client server python socket

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

Example 4: python3 socket server

import socket
import os

sock_file = "/tmp/python_socket"

if os.path.exists(sock_file):
    os.remove(sock_file)

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(sock_file)
sock.listen()
print("Listening...")
while True:
    conn, _addr = sock.accept()
    datagram = conn.recv(1024)
    request = datagram.decode('utf-8')
    conn.send(str("Back at you:"+request).encode('utf-8'))