{"id":16536833,"url":"https://github.com/shauryauppal/socket-programming-python","last_synced_at":"2025-03-21T09:32:16.589Z","repository":{"id":45860731,"uuid":"103724217","full_name":"shauryauppal/Socket-Programming-Python","owner":"shauryauppal","description":"Client Server running code described with comments here.","archived":false,"fork":false,"pushed_at":"2021-09-30T19:13:30.000Z","size":233,"stargazers_count":66,"open_issues_count":3,"forks_count":32,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-17T23:51:58.219Z","etag":null,"topics":["c","hacktoberfest","multithreading","python","socket-programming"],"latest_commit_sha":null,"homepage":"https://www.linkedin.com/in/shaurya-uppal/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shauryauppal.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-09-16T04:20:21.000Z","updated_at":"2025-03-03T02:38:40.000Z","dependencies_parsed_at":"2022-08-28T14:02:40.269Z","dependency_job_id":null,"html_url":"https://github.com/shauryauppal/Socket-Programming-Python","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shauryauppal%2FSocket-Programming-Python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shauryauppal%2FSocket-Programming-Python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shauryauppal%2FSocket-Programming-Python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shauryauppal%2FSocket-Programming-Python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shauryauppal","download_url":"https://codeload.github.com/shauryauppal/Socket-Programming-Python/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244772570,"owners_count":20508016,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","hacktoberfest","multithreading","python","socket-programming"],"created_at":"2024-10-11T18:33:37.804Z","updated_at":"2025-03-21T09:32:16.046Z","avatar_url":"https://github.com/shauryauppal.png","language":"Python","funding_links":["https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=UXSREFS2VFSWU"],"categories":[],"sub_categories":[],"readme":"# Guide to Socket Programming Introduction\n[![HitCount](http://hits.dwyl.io/shauryauppal/Socket-Programming-Python.svg)](https://github.com/shauryauppal/Socket-Programming-Python) [![MadeIn](https://img.shields.io/badge/MADE%20IN-PYTHON-darkblue.svg)](https://github.com/shauryauppal/Socket-Programming-Python) [![MadeIn](https://img.shields.io/badge/MADE%20IN-C-yellowgreen.svg)](https://github.com/shauryauppal/Socket-Programming-Python/tree/master/Socket_C) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)\n[![GitHub stars](https://img.shields.io/github/stars/shauryauppal/Socket-Programming-Python.svg)](https://github.com/shauryauppal/Socket-Programming-Python/stargazers)\n\n## Socket programming is started by socket library\n\n```\nimport socket\ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n```\n\n+ AF_INET refers to address family ipv4\n+ SOCK_STREAM meaning TCP protocol\n\n*****************\n\n## SERVER code\n+ s = socket.socket()\n   + It simply creates a new socket using the given address family,socket type and protocol number.\n+ port = 12345\n   + Reserves a port for computer\n+ s.bind('',port)\n  + 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.\n+ s.listen(5)\n   + Server can connect to 5 clients, 6th or more clients are rejected.\n+ s.accept()\n   + Return new socket object c and address\n+ s.close()\n  + Marks the socket closed, all future operaions on socket will be failed.\n\n #### OverView\n  ```\n #import library\n import socket\n\n s=socket.socket()\n port=12345\n s.bind('',port)\n s.listen(5)\n\n while True:\n   c,addr = s.accept()\n   data = c.recv(1024)\n   c.sendall(data)\n c.close()\n```\nServer uses `bind() , listen() , accept()`\n*************\n## Client Code\n\n+ First create socket object\n+ Give port number same as server\n+ connect() '127.0.0.1' local machine connection\n+ print s.recv(1024) #print data recv from socket\n+ close() connection\n```\n import socket\n s=socketsocket()\n port=12345\n s.connect('127.0.0.1',port)\n print s.recv(1024)\n s.close()\n```\n\n\u003cimg src = 'https://raw.githubusercontent.com/InternityFoundation/Socket-Programming-Python/master/1.%20String%20Reverse%20(Client-Server)%20Python/ReverseString.PNG' height = \"430px\" width = \"630px\"/\u003e\n\n ## Reference Link\n + [Explaination and sample program geeksforgeeks](http://www.geeksforgeeks.org/socket-programming-python/)\n + [Sample Program python socket programming](http://www.bogotobogo.com/python/python_network_programming_server_client.php)\n\n ****************\n ## CRC Socket PROGRAMMING\n [Article Link](https://www.geeksforgeeks.org/cyclic-redundancy-check-python/)\n\n \u003cimg src = 'https://raw.githubusercontent.com/InternityFoundation/Socket-Programming-Python/master/3.%20Client%20Server%20CRC%20code/CRC.PNG' height = \"430px\" width = \"630px\"/\u003e\n\n\n***************\n## Note - In **Socket_C** socket programming alternate C code is also added.\n\n***************************\n# SOCKET PROGRAMMING WITH MULTI-THREADING\n### Checkout My Article [Socket Programming Multi-Threading At Geeksforgeeks](http://www.geeksforgeeks.org/socket-programming-multi-threading-python/)\n\n## Socket Programming-\u003e\nIt 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.\n\n## What is a Thread?\nA thread is a light-weight process that does not require much memory overhead, they are cheaper than processes.\n\n## What is Multi-threading Socket Programming?\nMultithreading is a process of executing multiple threads simultaneously in a single process.\n\n## Multi-threading Modules : \nA *_thread module \u0026 threading module* is used for multi-threading in python, these modules help in synchronization and provide a lock to a thread in use.\n\n```\nfrom _thread import *\nimport threading\n```\nA lock object is created by-\u003e\n\n`print_lock = threading.Lock()`\n\nA 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.\n\nThe 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.\n\nLet's study client-server multithreading socket programming by code-\\\n*Note:-The code works with python3.*\n\n# Multi-threaded Server Code\n\n\n```\n# import socket programming library\nimport socket\n\n# import thread module\nfrom _thread import *\nimport threading\n\nprint_lock = threading.Lock()\n\n# thread fuction\ndef threaded(c):\n    while True:\n\n        # data received from client\n        data = c.recv(1024)\n        if not data:\n            print('Bye')\n\n            # lock released on exit\n            print_lock.release()\n            break\n\n        # reverse the given string from client\n        data = data[::-1]\n\n        # send back reversed string to client\n        c.send(data)\n\n    # connection closed\n    c.close()\n\n\ndef Main():\n    host = \"\"\n\n    # reverse a port on your computer\n    # in our case it is 12345 but it\n    # can be anything\n    port = 12345\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.bind((host, port))\n    print(\"socket binded to post\", port)\n\n    # put the socket into listening mode\n    s.listen(5)\n    print(\"socket is listening\")\n\n    # a forever loop until client wants to exit\n    while True:\n\n        # establish connection with client\n        c, addr = s.accept()\n\n        # lock acquired by client\n        print_lock.acquire()\n        print('Connected to :', addr[0], ':', addr[1])\n\n        # Start a new thread and return its identifier\n        start_new_thread(threaded, (c,))\n    s.close()\n\n\nif __name__ == '__main__':\n    Main()\n```\n```\nConsole Window:\nsocket binded to post 12345\nsocket is listening\nConnected to : 127.0.0.1 : 11600\nBye\n```\n# Client Code\n```\n# Import socket module\nimport socket\n\n\ndef Main():\n    # local host IP '127.0.0.1'\n    host = '127.0.0.1'\n\n    # Define the port on which you want to connect\n    port = 12345\n\n    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\n    # connect to server on local computer\n    s.connect((host,port))\n\n    # message you send to server\n    message = \"shaurya says geeksforgeeks\"\n    while True:\n\n        # message sent to server\n        s.send(message.encode('ascii'))\n\n        # messaga received from server\n        data = s.recv(1024)\n\n        # print the received message\n        # here it would be a reverse of sent message\n        print('Received from the server :',str(data.decode('ascii')))\n\n        # ask the client whether he wants to continue\n        ans = input('\\nDo you want to continue(y/n) :')\n        if ans == 'y':\n            continue\n        else:\n            break\n    # close the connection\n    s.close()\n\nif __name__ == '__main__':\n    Main()\n```\n\n```\nConsole Window:\nReceived from the server : skeegrofskeeg syas ayruahs\n\nDo you want to continue(y/n) :y\nReceived from the server : skeegrofskeeg syas ayruahs\n\nDo you want to continue(y/n) :n\n\nProcess finished with exit code 0\n```\nReference-\u003e\\\n\u003chttps://docs.python.org/2/library/thread.html\u003e\n\n*************************\n## Contributions\n\u003ca href=\"https://github.com/shauryauppal/Socket-Programming-Python/issues\"\u003e Issues \u003c/a\u003e and \u003ca href =\"https://github.com/shauryauppal/Socket-Programming-Python/pulls\"\u003e Pull requests \u003c/a\u003e are most welcome.\n\n*************\n\u003ca href=\"https://tracking.gitads.io/?repo=Socket-Programming-Python\"\u003e \u003cimg src=\"https://images.gitads.io/Socket-Programming-Python\" alt=\"GitAds\" width=\"400\" height=\"130\"/\u003e \u003c/a\u003e\n\n---\n\n### Author:\n#### Shaurya Uppal\nshauryauppal00111@gmail.com\n\nFeel free to mail me for any queries.\n\n#### If this helped you in any way gift me a cup of coffee :coffee:\n[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick\u0026hosted_button_id=UXSREFS2VFSWU)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshauryauppal%2Fsocket-programming-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshauryauppal%2Fsocket-programming-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshauryauppal%2Fsocket-programming-python/lists"}