TypeError:需要一个类似字节的对象,而不是套接字编程中的“ str”

时间:2018-11-26 23:08:05

标签: python python-3.x sockets

我试图在计算机上同时作为服务器和客户端运行此代码,但出现此错误。

TypeError: a bytes-like object is required, not 'str'

我是套接字编程的新手,所以我不太确定缺少什么。我认为这是一个问题,原因是我在两台服务器上都有两个不同的端口,但我已修复并且仍然无法正常工作。

这是服务器端

import socket, select

#Function to send message to all connected clients
def send_to_all (sock, message):
    #Message not forwarded to server and sender itself
    for socket in connected_list:
        if socket != server_socket and socket != sock :
            try :
                socket.send(message)
            except :
                # if connection not available
                socket.close()
                connected_list.remove(socket)

if __name__ == "__main__":
    name=""
    #dictionary to store address corresponding to username
    record={}
    # List to keep track of socket descriptors
    connected_list = []
    buffer =1024
    port =9999

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_socket.bind(("localhost", port))
    server_socket.listen(10) #listen atmost 10 connection at one time

    # Add server socket to the list of readable connections
    connected_list.append(server_socket)

    print ("\33[32m \t\t\t\tSERVER WORKING \33[0m") 

    while 1:
        # Get the list sockets which are ready to be read through select
        rList,wList,error_sockets = select.select(connected_list,[],[])

        for sock in rList:
            #New connection
            if sock == server_socket:
                # Handle the case in which there is a new connection recieved through server_socket
                sockfd, addr = server_socket.accept()
                name=sockfd.recv(buffer)
                connected_list.append(sockfd)
                record[addr]=""
                #print "record and conn list ",record,connected_list

                #if repeated username
                if name in record.values():
                    sockfd.send("\r\33[31m\33[1m Username already taken!\n\33[0m")
                    del record[addr]
                    connected_list.remove(sockfd)
                    sockfd.close()
                    continue
                else:
                    #add name and address
                    record[addr]=name
                    print ("Client (%s, %s) connected" % addr," [",record[addr],"]")
                    sockfd.send("\33[32m\r\33[1m Welcome to chat room. Enter 'tata' anytime to exit\n\33[0m")
                    send_to_all(sockfd, "\33[32m\33[1m\r "+name+" joined the conversation \n\33[0m")

            #Some incoming message from a client
            else:
                # Data from client
                try:
                    data1 = sock.recv(buffer)
                    #print "sock is: ",sock
                    data=data1[:data1.index("\n")]
                    #print "\ndata received: ",data

                    #get addr of client sending the message
                    i,p=sock.getpeername()
                    if data == "tata":
                        msg="\r\33[1m"+"\33[31m "+record[(i,p)]+" left the conversation \33[0m\n"
                        send_to_all(sock,msg)
                        print ("Client (%s, %s) is offline" % (i,p)," [",record[(i,p)],"]")
                        del record[(i,p)]
                        connected_list.remove(sock)
                        sock.close()
                        continue

                    else:
                        msg="\r\33[1m"+"\33[35m "+record[(i,p)]+": "+"\33[0m"+data+"\n"
                        send_to_all(sock,msg)

                #abrupt user exit
                except:
                    (i,p)=sock.getpeername()
                    send_to_all(sock, "\r\33[31m \33[1m"+record[(i,p)]+" left the conversation unexpectedly\33[0m\n")
                    print ("Client (%s, %s) is offline (error)" % (i,p)," [",record[(i,p)],"]\n")
                    del record[(i,p)]
                    connected_list.remove(sock)
                    sock.close()
                    continue

    server_socket.close()

这是客户端

import socket, select, string, sys

#Helper function (formatting)
def display() :
    you="\33[33m\33[1m"+" You: "+"\33[0m"
    sys.stdout.write(you)
    sys.stdout.flush()

def main():

    if len(sys.argv)<2:
        host = input("Enter host ip address: ")
    else:
        host = sys.argv[1]


    port =9999

    #asks for user name
    name=input("\33[34m\33[1m CREATING NEW ID\n Enter username: \33[0m")
    socketobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socketobj.settimeout(2)

    # connecting host
    try :
        socketobj.connect((host, port))
    except :
        print ("\33[31m\33[1m Can't connect to the server \33[0m")
        sys.exit()

    #if connected
    socketobj.send(name)
    display()
    while 1:
        socket_list = [sys.stdin, socketobj]

        # Get the list of sockets which are readable
        rList, wList, error_list = select.select(socket_list , [], [])

        for sock in rList:
            #incoming message from server
            if sock == socketobj:
                data = sock.recv(1024)
                if not data :
                    print ('\33[31m\33[1m \rDISCONNECTED!!\n \33[0m')
                    sys.exit()
                else :
                    sys.stdout.write(data)
                    display()

            #user entered a message
            else :
                msg=sys.stdin.readline()
                socketobj.send(msg)
                display()

if __name__ == "__main__":
    main()

这是我遇到的错误:

Enter host ip address: 127.0.0.1

CREATING NEW ID
Enter username: lydie
Traceback (most recent call last):
  File "<ipython-input-6-e1eec3734f59>", line 1, in <module>
    runfile('C:/Users/pc/.spyder-py3/clientlyd.py', wdir='C:/Users/pc/.spyder-py3')
  File "C:\Users\pc\Anaconda3\source\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)
  File "C:\Users\pc\Anaconda3\source\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/pc/.spyder-py3/clientlyd.py", line 58, in <module>
    main()
  File "C:/Users/pc/.spyder-py3/clientlyd.py", line 32, in main
    socketobj.send(name)
TypeError: a bytes-like object is required, not 'str'

0 个答案:

没有答案