Sending string via socket (python)

Sending string via socket (python)

import socket
from threading import *

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host =
port = 8000
print (host)
print (port)
serversocket.bind((host, port))

class client(Thread):
    def __init__(self, socket, address):
        self.sock = socket
        self.addr = address

    def run(self):
        while 1:
            print(Client sent:, self.sock.recv(1024).decode())
            self.sock.send(bOi you sent something to me)

print (server started and listening)
while 1:
    clientsocket, address = serversocket.accept()
    client(clientsocket, address)

This is a very VERY simple design for how you could solve it.
First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

import socket

s = socket.socket()
while True:
    str = raw_input(S: )
    if(str == Bye or str == bye):
    print N:,s.recv(1024).decode()

import socket

s = socket.socket()
port = 12345
s.bind((, port))
c, addr = s.accept()
print Socket Up and running with a connection from,addr
while True:
    rcvdData = c.recv(1024).decode()
    print S:,rcvdData
    sendData = raw_input(N: )
    if(sendData == Bye or sendData == bye):

This should be the code for a small prototype for the chatting app you wanted.
Run both of them in separate terminals but then just check for the ports.

Sending string via socket (python)

This piece of code is incorrect.

while 1:
    (clientsocket, address) = serversocket.accept()
    print (connection found!)
    data = clientsocket.recv(1024).decode()
    print (data)

The call on accept() on the serversocket blocks until theres a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.

Thats the reason the recv works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted – maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.

Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.

Leave a Reply

Your email address will not be published. Required fields are marked *