Communicating with multiple clients using one TCP socket pyt

bobbdeep anudeepsm at gmail.com
Mon Mar 30 04:43:56 EDT 2015


I am using TCP sockets to communicate between my server and clients. The server code and socket code are as below:

server:

from socket import *

HOST = 'xx.xx.xx.xx'
PORT = 1999
serversocket = socket(AF_INET,SOCK_STREAM)
serversocket.bind((HOST,PORT))
print 'bind success'
serversocket.listen(5)
print 'listening'
while True:
    (clientsocket, address) = serversocket.accept()
    print ("Got client request from",address)
    #clientsocket.send('True')
    data = clientsocket.recv(1024)
    print data
    clientsocket.send('True')
    clientsocket.close()


client:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port on the server given by the caller
server_address = ('xx.xx.xx.xx', 1999)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

try:

    message = 'This is the message.  It will be repeated.'
    print >>sys.stderr, 'sending' 
    for x in range (0,1):
      name=raw_input ('what is ur name')
      print type(name)
      sock.send(name)
      print sock.recv(1024)

finally:
    sock.close()


I am able to communicate with the server from client and able to send and receive data. But the problem I am facing is that I am not able to send and receive data continuously from the server. I have to restart my client code on my laptop to send and receive data again from the server. The way the above client code is working is that when I give a keyboard input, then the socket sends data to server and server responds back. But in the client code, in the for loop if I do two iterations, for the second iteration the data I enter from keyboard is not reaching server. I need to restart my client code to send data again. How do I fix this ?

Also, when once client is connected to the server, the other cannot connect to the server. Any ideas on how to do this ?



More information about the Python-list mailing list