0
import socket
import sys

host=''  # Symbolic name meaning all available interfaces
port=7777  #random port

#creating socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "socket created"

#binding
try:
    sock.bind((host,port))
except socket.error,msg:
    print "Bind failed,Error no:"+str(msg[0])+"error:-"+str(msg[1])
    sys.exit()
print "Bind successful"

sock.listen(10)
print "Listening" # it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected.
conn, addr=sock.accept()#accept new connection
print "connected to "+str(addr[0])+":"+str(addr[1])

#receive from client
data=conn.recv(1024)
print "received-"+data
conn.sendall(data*2)

#terminate
conn.close()
sock.close()

the above is the code for receiving data from a client and replying for it. i used cmd with "telnet localhost 7777" to connect. then i wanted to send a simple "hello world" message but i just typed "h" and i got a reply and the connection was terminated.

my_code.py output

Hidde
  • 11,493
  • 8
  • 43
  • 68
Aashish
  • 1
  • 1

1 Answers1

0

It has worked for me. Is your socketClient working correctly?

import socket
string='hello world'
print type(string)
HOST, PORT = 'localhost', 7777
# SOCK_STREAM == a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.setblocking(0)  # optional non-blocking
sock.connect((HOST, PORT))
sock.send(string)
reply = sock.recv(1024)  # limit reply to 16K
print(reply)
sock.close()
return reply
ishmaelMakitla
  • 3,784
  • 3
  • 26
  • 32
DarkShadow
  • 1
  • 1
  • 1