0

I a server and client for a socket connection in Python,

client:

import socket
import sys
from sys import stdin

serv = 'ip goes here'
port = 8888
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((serv, port))


def prompt():
    sys.stdout.write('<You> ')
    sys.stdout.flush()


def send(x):
    sock.sendall(x)
    rec = 0
    ex = len(x)
    while rec < ex:
        data = sock.recv(16)
        rec += len(data)

while 1:
    if sock:
        data = sock.recv(16)
        if len(data) == 0:
            pass
        print '<Server> %s' % data
        prompt()
        msg = stdin.readline()
        sock.sendall(msg)

The way I have it now, if you say something on one client, it will send "alphabet" to both clients but the other clients will not receive that until they send a new message as it is waiting for stdin.readline() to occur. I was wondering how to make it so the clients will always receive data from the server, and will see it without having to have stdin.readline() happen first.

Thanks

CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
user2896775
  • 182
  • 1
  • 1
  • 8
  • You're new so here's some advice. First, pastebin is not ok. You need to include your code, see MCVE: http://stackoverflow.com/help/mcve. Second, you need to pick out the little bit of the code that your problem is related to (again, see MCVE). – CrazyCasta Jul 05 '15 at 17:14
  • To answer your question of how to do this though, the generally excepted means is to use threads. In one thread you'll have `stdin.readline()`, and in the other you'll have `data = sock.recv(16)`. You'll have to coordinate between the threads to decide how to print stuff out so you don't print out two things at the same time. – CrazyCasta Jul 05 '15 at 17:22
  • Ah, sorry about that. Next time I will follow MCVE. Made it work like you said with threading, thanks. – user2896775 Jul 05 '15 at 17:46

1 Answers1

2

Achieved what I wanted by using threads as suggested by CrazyCasta

def receiving():
    while 1:
        if sock:
            data = sock.recv(16)
            if len(data) == 0:
                pass
            print '<Server> %s' % data


def sending():
    while 1:
        msg = stdin.readline()
        sock.sendall(msg)

t1 = Thread(target=receiving)
t2 = Thread(target=sending)

t1.start()
t2.start()
user2896775
  • 182
  • 1
  • 1
  • 8