저는 Python을 처음 사용하고 간단한 채팅 응용 프로그램을 작성하려고합니다. 연결된 클라이언트와 메시지를주고받는 스레드를 실행하는 서버를 특징으로합니다. 서버에 메시지를 보내고 받아들이는 두 개의 스레드를 실행하는 클라이언트.소켓 채팅 응용 프로그램의 Python 스레드가 시작되지 않습니다.
이import socket
import sys
import thread
def receiveAndDeliverMessage(conn):
while True:
data = conn.recv(1040)
if not data: break
print(data)
conn.send(data)
conn.close
HOST = '' # Localhost
PORT = 8888 # Arbitrary non-privileged port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP/IP socket
print 'Socket created'
#Bind socket to local host and port
try:
sock.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
sock.listen(10)
print 'Socket now listening'
# Create threads for receiving a connection from client and receiving data from client
while True:
connection, address = sock.accept() #Accept method returns a tupule containing a new connection and the address of the connected client
print 'Connected with ' + address[0] + ':' + str(address[1])
try:
thread.start_new_thread(receiveAndDeliverMessage, (connection))
except:
print ("Error: unable to start thread")
sock.close()
가 클라이언트 :
이#Socket client example in python
import socket #for sockets
import sys #for exit
import thread
def sendMessage():
count = 0
while (count < 3):
message = raw_input('Write message to send to server: ');
count = count + 1
print 'message '+str(count)+': '+(message)
try :
#Send the whole string
sock.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message sent successfully to server'
def receiveMessage():
reply = sock.recv(1024)
print reply#Print the message received from server
#create an INET, STREAMing socket
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
serverHost = 'localhost'
serverPort = 8888
try:
remote_ip = socket.gethostbyname(serverHost)
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
sock.connect((remote_ip , serverPort))
print 'Socket Connected to ' + serverHost + ' on ip ' + remote_ip
try:
thread.start_new_thread(receiveMessage,())
except:
print ("Error: unable to start receive message thread")
try:
thread.start_new_thread(sendMessage,())
except:
print ("Error: unable to start send message thread")
sock.close()#Close socket to send eof to server
는 이제 클라이언트가 열릴 때마다이 대신 receiveAndDelivermessage 기능은 서버에서 실행되는 실행 스레드의 예외가 발생됩니다 여기
는 서버 코드를입니다 . 그래서 "오류 : 스레드를 시작할 수 없습니다."라는 메시지가 나타납니다. 나는 왜 예외가 던져 지는지 이해하지 못한다. 어쩌면 스레드가 작동하는 방식을 아직 파악하지 못했을 수도 있습니다. 어떤 도움이라도 대단히 감사합니다. 또한 클라이언트가 열릴 때마다 서버 연결이 설정된 후 즉시 종료됩니다.
당신이 모든 당신이 돈 때문에 제외 캐치를 사용을 코드에서 발생하는 사소한 오류를 보지 말고,'(연결)'은 하나의 요소를 가진 튜플이 아니며 단지'connection'이므로 잘못된 인수 유형 때문에'thread.start_new_thread'가 유형 오류를 던지고 있습니다. –
@ Tadhg McDonald-Jensen 알았어. 그것을 수정 (연결, 주소) 그리고 지금은 잘 작동하는 것 같습니다. 아직도 얻지 못하는 이유는 서버와의 연결이 설정되는 즉시 클라이언트 응용 프로그램이 끝나는 이유입니다. sendMessage() 메서드를 트리거 할 것으로 예상되는 두 번째 스레드는 전혀 수행하지 않는 것 같습니다. –