【问题标题】:python network threading simple chat, waits for user to press enter then gets messagespython网络线程简单聊天,等待用户按回车然后获取消息
【发布时间】:2014-05-07 02:38:44
【问题描述】:

所以现在为了收到您的消息,您需要收到一个

我的老师的指令是(主要)“修改循环,使其仅侦听键盘输入,然后将其发送到服务器。” 我做了其余的,但不明白这一点,...帮助?

import socket
import select
import sys
import threading

'''
Purpose:  Driver
parameters: none
returns: none
'''

def main():
    host = 'localhost'
    port = 5000
    size = 1024
    #open a socket to the client.
    try:
        clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        clientSock.connect((host,port))
        #exit on error
    except socket.error, (value,message):
        if clientSock :
            clientSock.close()
            print "Could not make connection: " + message
        sys.exit(1) 

    thread1 = ClientThread() 
    thread1.start() 

    while True:
        #wait for keyboard input
        line = raw_input()
        #send the input to the server unless its only a newline
        if line != "\n":
            clientSock.send(line)
        #wait to get something from the server and print it
        data = clientSock.recv(size)
        print data
class ClientThread(threading.Thread): 

 ''' 
 Purpose: the constructor 
 parameters: the already created and connected client socket 
 returns: none 
 ''' 

def __init__(self, clientSocket): 
    super(ClientThread, self).__init__() 
    self.clientSocket = clientSocket 
    self.stopped = False 



def run(self): 
    while not self.stopped: 
        self.data = self.clientSocket.recv(1024) 
        print self.data 



main()

【问题讨论】:

  • 我能提供更多信息不应该那么复杂吗?
  • 你能描述一下这个程序的假定行为吗?怎么了?

标签: python multithreading sockets python-2.7 python-3.x


【解决方案1】:

我假设您的目的是创建一个启动两个线程的程序,一个(客户端线程)接收键盘输入并发送到另一个(服务器线程),服务器线程打印出它收到的所有内容。

根据我的假设,您首先需要启动一个 ServerThread 侦听端口(这与您的“ClientThread”所做的不同)。这是一个例子:

import socket
import threading

def main():
    host = 'localhost'
    port = 5000
    size = 1024

    thread1 = ServerThread(host, port, size) 
    thread1.start() 

    #open a socket for client
    try:
        clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        clientSock.connect((host,port))
    except socket.error, (value,message):
        if clientSock:
            clientSock.close()
            print "Could not connect to server: " + message
        sys.exit(1) 

    while True:
        #wait for keyboard input
        line = raw_input()
        #send the input to the server unless its only a newline
        if line != "\n":
            clientSock.send(line)
            # Is server supposed to send back any response?
            #data = clientSock.recv(size)
            #print data
        if line == "Quit":
            clientSock.close()
            break

class ServerThread(threading.Thread): 
    def __init__(self, host, port, size): 
        super(ServerThread, self).__init__() 
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((host, port))
        self.sock.listen(1)
        self.data_size = size
        self.stopped = False 

    def run(self): 
        conn, addr = self.sock.accept()
        print 'Connected by', addr
        while not self.stopped: 
            data = conn.recv(self.data_size)
            if data == 'Quit':
                print 'Client close the connection'
                self.stopped = True
            else:
                print 'Server received data:', data
                # Is server supposed to send back any response?
                #conn.sendall('Server received data: ' + data)
        conn.close()

if __name__ == '__main__':
    main()

这些是输出:

Connected by ('127.0.0.1', 41153)
abc
Server received data: abc
def
Server received data: def
Quit
Client close the connection

您可以在此处查看有关 Python 套接字的更多详细信息:https://docs.python.org/2/library/socket.html?#example

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多