我正在构建一个供个人使用的聊天服务器,我也正在建立一个客户端。输入字符串并将其发送到服务器后,我收到错误,但我不明白它是什么意思或如何解决它。有人可以帮忙吗?
客户代码:
# chat_client.py
msg=""
import sys
import socket
import select
host="127.0.0.1"
port=9999
s=socket.socket()
s.connect((host,port))
while msg!="EXIT":
msg=input("<You> ")
s.send((str(msg)))
print(s.recv(1024))
s.close
服务器代码:
import socket, subprocess
import threading
bind_ip="127.0.0.1"
bind_port= 9999
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print("[*] Listening on %s:%d" % (bind_ip,bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print ("[*] Recieved: %s" %request)
client_socket.send("ACK!")
client_socket.close()
while True:
client,addr=server.accept()
print("[*] Accepted Connection from %s:%d" % (addr[0],addr[1]))
client_handler = threading.Thread(target=handle_client(client,))
client_handler.start()
错误消息:
<You> hello
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\python 2.7 socket stuff\TCP_CLIENT.py", line 14,
in <module>
msg=input("<You> ")
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
答案 0 :(得分:0)
使用raw_input()
代替input()
。
input()
功能很危险,因为eval()
用户的输入不是您想要的。从文档(强调我的):
<强>
input([prompt])
强>
相当于eval(raw_input(prompt))
。此功能不会捕获用户错误。如果输入在语法上不合法,则会引发
SyntaxError
。 如果评估过程中出现错误,可能会引发其他异常。考虑将
raw_input()
函数用于用户的一般输入。
答案 1 :(得分:0)
Python2的input
尝试评估输入的值。如果您输入hello
,它将搜索预定义的hello
变量。
您应该使用raw_input
代替:
msg = raw_input("<You> ")
答案 2 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 4444
int main(){
int clientSocket, ret;
struct sockaddr_in serverAddr;
char buffer[1024];
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if(clientSocket < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Client Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(ret < 0){
printf("[-]Error in connection.\n");
exit(1);
}
printf("[+]Connected to Server.\n");
for(uint64_t i = 0; i < torrent.block_count; i++){
printf("Client: \t");
scanf("%s", &buffer[0]);
send(clientSocket, buffer, strlen(buffer), 0);
if(strcmp(buffer, ":exit") == 0){
close(clientSocket);
printf("[-]Disconnected from server.\n");
exit(1);
}
if(recv(clientSocket, buffer, 1024, 0) < 0){
printf("[-]Error in receiving data.\n");
}else{
printf("Server: \t%s\n", buffer);
}
}
//有些人在客户端循环中遇到问题尝试添加这个只是为了查看块是否正确计数
uint64_t block_counter = 0;
counter_congf = true;
while (block_counter < torrent.block_count && ct == true) {
if (torrent.block_map[block_counter] != true)
counter_congf = false;
else block_counter ++;
}
}
close(client_sockfd);
返回0; }