All Projects → shauryauppal → Socket-Programming-Python

shauryauppal / Socket-Programming-Python

Licence: other
Client Server running code described with comments here.

Programming Languages

python
139335 projects - #7 most used programming language
Rich Text Format
576 projects
c
50402 projects - #5 most used programming language

Projects that are alternatives of or similar to Socket-Programming-Python

Chatroom-in-C
A simple Chatroom built in C programming language. The program is built uses multithreading for handling multiple clients.
Stars: ✭ 51 (+6.25%)
Mutual labels:  multithreading, socket-programming
lucy job system
Fiber-based job system with extremely simple API
Stars: ✭ 78 (+62.5%)
Mutual labels:  multithreading
wasm-bindgen-rayon
An adapter for enabling Rayon-based concurrency on the Web with WebAssembly.
Stars: ✭ 257 (+435.42%)
Mutual labels:  multithreading
hostbase
A Ruby GUI based on advanced rogue AP attack using the WPS
Stars: ✭ 43 (-10.42%)
Mutual labels:  multithreading
Simplified-JNA
Multi-threaded JNA hooks and simplified library access to window/key/mouse functions.
Stars: ✭ 30 (-37.5%)
Mutual labels:  multithreading
Planeverb
Project Planeverb is a CPU based real-time wave-based acoustics engine for games. It comes with an integration with the Unity Engine.
Stars: ✭ 22 (-54.17%)
Mutual labels:  multithreading
TaskManager
A C++14 Task Manager / Scheduler
Stars: ✭ 81 (+68.75%)
Mutual labels:  multithreading
bikeshed
Lock free hierarchical work scheduler
Stars: ✭ 78 (+62.5%)
Mutual labels:  multithreading
DynAdjust
Least squares adjustment software
Stars: ✭ 43 (-10.42%)
Mutual labels:  multithreading
theater
Actor framework for Dart. This package makes it easier to work with isolates, create clusters of isolates.
Stars: ✭ 29 (-39.58%)
Mutual labels:  multithreading
variadic future
Variadic, completion-based futures for C++17
Stars: ✭ 41 (-14.58%)
Mutual labels:  multithreading
ThreadPinning.jl
Pinning Julia threads to cores
Stars: ✭ 23 (-52.08%)
Mutual labels:  multithreading
dystopia
Low to medium multithreaded Ubuntu Core honeypot coded in Python.
Stars: ✭ 59 (+22.92%)
Mutual labels:  multithreading
workerpoolxt
Concurrency limiting goroutine pool without upper limit on queue length. Extends github.com/gammazero/workerpool
Stars: ✭ 15 (-68.75%)
Mutual labels:  multithreading
euler2d kokkos
Simple 2d finite volume solver for Euler equations using c++ kokkos library
Stars: ✭ 27 (-43.75%)
Mutual labels:  multithreading
disruptor-billing-example
Example LMAX Disruptor spring-boot project that uses disruptor-spring-manager framework
Stars: ✭ 56 (+16.67%)
Mutual labels:  multithreading
ObviousAwait
🧵 Expressive aliases to ConfigureAwait(true) and ConfigureAwait(false)
Stars: ✭ 55 (+14.58%)
Mutual labels:  multithreading
L2-Emulator
Implementing a Layer-2 Emulator in C using Graphs and LinkedList
Stars: ✭ 17 (-64.58%)
Mutual labels:  socket-programming
TradingMachine
TradingMachine is a mini-trading system simulation, whose components (market data and order feeds, FIX acceptor and initiator, back-end for filled orders) interact by queues and topics.
Stars: ✭ 26 (-45.83%)
Mutual labels:  multithreading
Multithreaded-Reddit-Image-Downloader
Does exactly what it says on the tin.
Stars: ✭ 38 (-20.83%)
Mutual labels:  multithreading

Guide to Socket Programming Introduction

HitCount MadeIn MadeIn PRs Welcome GitHub stars

Socket programming is started by socket library

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  • AF_INET refers to address family ipv4
  • SOCK_STREAM meaning TCP protocol

SERVER code

  • s = socket.socket()
    • It simply creates a new socket using the given address family,socket type and protocol number.
  • port = 12345
    • Reserves a port for computer
  • s.bind('',port)
    • We binded our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
  • s.listen(5)
    • Server can connect to 5 clients, 6th or more clients are rejected.
  • s.accept()
    • Return new socket object c and address
  • s.close()
    • Marks the socket closed, all future operaions on socket will be failed.

OverView

#import library
import socket

s=socket.socket()
port=12345
s.bind('',port)
s.listen(5)

while True:
 c,addr = s.accept()
 data = c.recv(1024)
 c.sendall(data)
c.close()

Server uses bind() , listen() , accept()


Client Code

  • First create socket object
  • Give port number same as server
  • connect() '127.0.0.1' local machine connection
  • print s.recv(1024) #print data recv from socket
  • close() connection
 import socket
 s=socketsocket()
 port=12345
 s.connect('127.0.0.1',port)
 print s.recv(1024)
 s.close()

Reference Link


CRC Socket PROGRAMMING

Article Link


Note - In Socket_C socket programming alternate C code is also added.


SOCKET PROGRAMMING WITH MULTI-THREADING

Checkout My Article Socket Programming Multi-Threading At Geeksforgeeks

Socket Programming->

It helps us to connect a client to a server. Client is message sender and receiver and server is just a listener that works on data sent by client.

What is a Thread?

A thread is a light-weight process that does not require much memory overhead, they are cheaper than processes.

What is Multi-threading Socket Programming?

Multithreading is a process of executing multiple threads simultaneously in a single process.

Multi-threading Modules : 

_thread module & threading module is used for multi-threading in python, these modules help in synchronization and provide a lock to a thread in use.

from _thread import *
import threading

A lock object is created by->

print_lock = threading.Lock()

A lock has two states, "locked" or "unlocked". It has two basic methods acquire() and release(). When the state is unlocked print_lock.acquire() is used to change state to locked and print_lock.release() is used to change state to unlock.

The function thread.start_new_thread() is used to start a new thread and return its identifier. The first argument is the function to call and its second argument is a tuple containing the positional list of arguments.

Let's study client-server multithreading socket programming by code-
Note:-The code works with python3.

Multi-threaded Server Code

# import socket programming library
import socket

# import thread module
from _thread import *
import threading

print_lock = threading.Lock()

# thread fuction
def threaded(c):
    while True:

        # data received from client
        data = c.recv(1024)
        if not data:
            print('Bye')

            # lock released on exit
            print_lock.release()
            break

        # reverse the given string from client
        data = data[::-1]

        # send back reversed string to client
        c.send(data)

    # connection closed
    c.close()


def Main():
    host = ""

    # reverse a port on your computer
    # in our case it is 12345 but it
    # can be anything
    port = 12345
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host, port))
    print("socket binded to post", port)

    # put the socket into listening mode
    s.listen(5)
    print("socket is listening")

    # a forever loop until client wants to exit
    while True:

        # establish connection with client
        c, addr = s.accept()

        # lock acquired by client
        print_lock.acquire()
        print('Connected to :', addr[0], ':', addr[1])

        # Start a new thread and return its identifier
        start_new_thread(threaded, (c,))
    s.close()


if __name__ == '__main__':
    Main()
Console Window:
socket binded to post 12345
socket is listening
Connected to : 127.0.0.1 : 11600
Bye

Client Code

# Import socket module
import socket


def Main():
    # local host IP '127.0.0.1'
    host = '127.0.0.1'

    # Define the port on which you want to connect
    port = 12345

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    # connect to server on local computer
    s.connect((host,port))

    # message you send to server
    message = "shaurya says geeksforgeeks"
    while True:

        # message sent to server
        s.send(message.encode('ascii'))

        # messaga received from server
        data = s.recv(1024)

        # print the received message
        # here it would be a reverse of sent message
        print('Received from the server :',str(data.decode('ascii')))

        # ask the client whether he wants to continue
        ans = input('\nDo you want to continue(y/n) :')
        if ans == 'y':
            continue
        else:
            break
    # close the connection
    s.close()

if __name__ == '__main__':
    Main()
Console Window:
Received from the server : skeegrofskeeg syas ayruahs

Do you want to continue(y/n) :y
Received from the server : skeegrofskeeg syas ayruahs

Do you want to continue(y/n) :n

Process finished with exit code 0

Reference->
https://docs.python.org/2/library/thread.html


Contributions

Issues and Pull requests are most welcome.


GitAds


Author:

Shaurya Uppal

[email protected]

Feel free to mail me for any queries.

If this helped you in any way gift me a cup of coffee

paypal

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].