2016-06-29 186 views
2

我正在編程一個基本的聊天程序。這樣做的目標是首先通過啓動server.py腳本來設置服務器,然後在後臺運行該服務器。然後用戶啓動client.py腳本並選擇一個名稱,然後開始鍵入一條消息併發送它。問題是當我嘗試發送它時會返回這個錯誤。Python錯誤:無法將字節隱式轉換爲字符串

Traceback (most recent call last): 
    File "C:\Users\Hello\AppData\Local\Programs\Python\Python35-32\client.py", line 38, in <module> 
    s.sendto(alias + ': ' + message.encode() , server) 
TypeError: Can't convert 'bytes' object to str implicitly 

這裏的server.py腳本---

import socket 
import time 

host = '127.0.0.1' 
port = 47015 

clients = [] 
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host, port)) 
s.setblocking(0) 

qutting = False 
print("Server Started") 

while not qutting: 
    try: 
     data, addr = s.recvfrom(1024) 
     if 'Quit' in str(data): 
      qutting = True 
     if addr not in clients: 
      clients.append(addr) 
     print(time.ctime(time.time()) + str(addr) + ": :" + str(data)) 
     for client in clients: 
      s.sendto(data, client) 
    except: 
     pass 
s.close() 

那麼client.py腳本----

import socket 
import threading 
import time 


tLock = threading.Lock() 
shutdown = False 

def recieving(name, sock): 
    while not shutdown: 
     try: 
      tLock.acquire() 
      while True: 
       data, addr = sock.recvfrom(1024) 
       data.decode() 
       print(str(data)) 
     except: 
      pass 
     finally: 
      tLock.release() 

host = '127.0.0.1' 
port = 0 

server = ("127.0.0.1", 47015) 

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
s.bind((host, port)) 
s.setblocking(0) 

rT = threading.Thread(target=recieving, args=('RecvThread', s)) 
rT.start() 

alias = input("Name: ") 
message = input(alias + "->") 
while message != 'q': 
    if message != '': 
     s.sendto(alias + ': ' + message.encode() , server) 
    tLock.acquire() 
    message = input(alias + '->') 
    tLock.release() 
    time.sleep(0.2) 

shutdown = True 
rT.join() 
s.close() 

所以,如果你有任何想法如何解決這個問題將不勝感激也有一個側面的問題是有沒有辦法讓接收線程一直運行,所以它主動更新聊天?

回答

0

的問題是在這條線:

s.sendto(alias + ': ' + message.encode() , server) 

要轉換messagebytes,但隨後要添加未轉換的字符串爲bytes對象。這是一個無效的操作,因爲錯誤信息告訴你,因爲bytes不能明確地轉換爲字符串。嘗試編碼整個事情:

s.sendto((alias + ': ' + message).encode() , server) 
相關問題