0

Someone can add to my Example under, the code that define the Client socket try to connect to the server for 2 seconds please ? I read about that and i don't successful to do that, because of that i ask for an example.

Example:

Client:

import socket

TCP_IP = '127.0.0.1'

TCP_PORT = 7777

BUFFER_SIZE = 1024

MESSAGE = "Hello, World!"

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

s.connect((TCP_IP, TCP_PORT))

s.send(MESSAGE)

data = s.recv(BUFFER_SIZE)

s.close()

print "received data:", data

Server:

import socket

TCP_IP = '127.0.0.1'

TCP_PORT = 7777

BUFFER_SIZE = 20


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

s.bind((TCP_IP, TCP_PORT))

s.listen(1)

conn, addr = s.accept()

print 'Connection address:', addr

while 1:

    data = conn.recv(BUFFER_SIZE)

    if not data: break

    print "received data:", data

    conn.send(data)

conn.close()

Thank you.

MultiPython
  • 71
  • 3
  • 7
  • We need to see your server-side code as well. I ran your code, and the obvious result was a complaint about lack of server-side program. – Yotam Jul 13 '13 at 14:28

1 Answers1

1

Instead of having two separate python files, you can have a single file but put the server and client in separate threads. sys.stdout.write is used instead of print due some concurrency issue with print being buffered (it mixes strings).

import threading
import socket
import sys

class socket_server(threading.Thread):
    TCP_IP = "127.0.0.1"
    TCP_PORT = 7777
    BUFFER_SIZE = 20
    daemon = True

    def run(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((self.TCP_IP, self.TCP_PORT))
        s.listen(1)

        conn, addr = s.accept()
        (ip, port) = addr

        sys.stdout.write("%s connection address: IP %s on Port %d\n" % (self.__class__.__name__, ip, port))

        data = True
        while data:

            data = conn.recv(self.BUFFER_SIZE)

            if data:
                sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
                send_data = data.upper()
                sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, send_data))
                conn.send(send_data)

        conn.close()

class socket_client(threading.Thread):
    TCP_IP = "127.0.0.1"
    TCP_PORT = 7777
    BUFFER_SIZE = 1024
    TIMEOUT = 2.0
    MESSAGE = "Hello, World!"

    def run(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(self.TIMEOUT)
        s.connect((self.TCP_IP, self.TCP_PORT))
        sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, self.MESSAGE))
        s.send(self.MESSAGE)

        data = s.recv(self.BUFFER_SIZE)

        s.close()

        if data:
            sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))

server = socket_server()
client = socket_client()

server.start()
client.start()
dilbert
  • 3,008
  • 1
  • 25
  • 34