我知道python,並試圖進入更復雜的東西。我發現這個代碼,它應該可以工作。我收到客戶端第14行的錯誤,返回mrecv ValueError:int()的基數爲10的無效文字; ''python套接字初學者
我有兩個文件分開,然後調用服務器,然後客戶端。當我運行他們的服務器只是說 關閉 和客戶說
recieved->再見!!! 並沒有任何反應,但是當我在客戶端輸入hello時,我得到了上面顯示的錯誤。我可能會/可能做錯了什麼,這是我第一次使用套接字或服務器或其他方法做任何事情。如果你知道我在做什麼錯,請幫忙,如果你有任何其他好的網站或教程對我來說,我將不勝感激。這裏是所有的代碼(不是我)
蟒蛇插座聊天例如, 作者:ANKUR Shrivastava, 許可證:GPL v3的
服務器
import socket
import threading
import time
SIZE = 4
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.bind(('127.0.0.1',5432))
soc.listen(5)
class CThread(threading.Thread):
def __init__(self,c):
threading.Thread.__init__(self)
self.conn = c
self.stopIt=False
def mrecv(self):
data = self.conn.recv(SIZE)
self.conn.send('OK')
msg = self.conn.recv(int(data))
return msg
def run(self):
while not self.stopIt:
msg = self.mrecv()
print 'recieved-> ',msg
def setConn(con1,con2):
dict={}
state = con1.recv(9)
con2.recv(9)
if state =='WILL RECV':
dict['send'] = con1 # server will send data to reciever
dict['recv'] = con2
else:
dict['recv'] = con1 # server will recieve data from sender
dict['send'] = con2
return dict
def msend(conn,msg):
if len(msg)<=999 and len(msg)>0:
conn.send(str(len(msg)))
if conn.recv(2) == 'OK':
conn.send(msg)
else:
conn.send(str(999))
if conn.recv(2) == 'OK':
conn.send(msg[:999])
msend(conn,msg[1000:]) # calling recursive
(c1,a1) = soc.accept()
(c2,a2) = soc.accept()
dict = setConn(c1,c2)
thr = CThread(dict['recv'])
thr.start()
try:
while 1:
msend(dict['send'],raw_input())
except:
print 'closing'
thr.stopIt=True
msend(dict['send'],'bye!!!')# for stoping the thread
thr.conn.close()
soc.close()
客戶
import socket
import threading
SIZE =4
class client(threading.Thread):
def __init__(self,c):
threading.Thread.__init__(self)
self.conn = c
self.stopIt = False
def mrecv(self):
data = self.conn.recv(SIZE)
self.conn.send('OK')
return self.conn.recv(int(data))
def run(self):
while not self.stopIt:
msg = self.mrecv()
print 'recieved-> ',msg
soc1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc1.connect(('127.0.0.1',5432))
soc1.send('WILL SEND') # telling server we will send data from here
soc2 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc2.connect(('127.0.0.1',5432))
soc2.send('WILL RECV') # telling server we will recieve data from here
def msend(conn,msg):
if len(msg)<=999 and len(msg)>0:
conn.send(str(len(msg)))
if conn.recv(2) == 'OK':
conn.send(msg)
else:
conn.send(str(999))
if conn.recv(2) == 'OK':
conn.send(msg[:999])
msend(conn,msg[1000:]) # calling recursive
thr = client(soc2)
thr.start()
try:
while 1:
msend(soc1,raw_input())
except:
print 'closing'
thr.stopIt=True
msend(soc1,'bye!!') # for stoping the thread
thr.conn.close()
soc1.close()
soc2.close()
我嘗試輸入一個數字,它給了我同樣的錯誤。當我從行中取出int並運行客戶端時,它說它必須是一個數字......任何其他想法?
該代碼似乎爲我工作。 – 2012-08-06 01:59:09
真的嗎?你如何運行/調用它? – Tom 2012-08-06 02:03:09
你的寫作。我試圖打字,所以現在我犯了一些小錯誤。應該有這個想法。謝謝 – Tom 2012-08-06 02:13:56