我想从Android
客户端向服务器python
发送一个字符串。但我发现了这个错误。请指导我!
不允许发送或接收数据的请求,因为套接字未连接(使用sendto调用在数据报套接字上发送时)没有提供地址
客户端
import android.util.Log;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class client {
private String serverIpAddress = "172.**.*.***";
private boolean connected = false;
private int serverPort = 65534;
protected void connect() {
if (!connected) {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
System.out.println("server addr " +serverAddr);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverIpAddress,serverPort);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String sendMessage = 2 + "\n";
out.write(sendMessage);
out.flush();
System.out.println("Message sent to the server : "+sendMessage);
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
服务器
import socket
import threading
import json
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.host, self.port))
print("Listening.....")
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
print("Accepted from :: "+str(address))
data = self.sock.recv(1024)
print ("received data:", str(data))
if __name__ == "__main__":
ThreadedServer('172.**.*.***',65534).listen()
我被困住了!
编辑1 信用:j4ck
import socket
import threading
import socketserver
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = str(self.request.recv(1024), 'ascii')
cur_thread = threading.current_thread()
response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = "localhost", 0
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print("Server loop running in thread:", server_thread.name)
服务器将关闭。如何使这个服务器为所有请求活着?我想使用套接字从Android
发送请求。我想,一旦请求到达服务器,服务器应该使一个类的线程不是一个函数。
答案 0 :(得分:0)
首先,您正在导入threading
模块,但似乎根本没有使用它。
我建议您使用the socketserver
module,因为它更方便,并为您做了一些事情。
线程版本将使用mixin
并且看起来像这样(来自上面链接的python文档):
import socket
import threading
import socketserver
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = str(self.request.recv(1024), 'ascii')
cur_thread = threading.current_thread()
response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
# This is a dummy client to show the functionality and is not required, should you choose to implement it
def client(ip, port, message):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((ip, port))
sock.sendall(bytes(message, 'ascii'))
response = str(sock.recv(1024), 'ascii')
print("Received: {}".format(response))
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "localhost", 0
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print("Server loop running in thread:", server_thread.name)
client(ip, port, "Hello World 1")
client(ip, port, "Hello World 2")
client(ip, port, "Hello World 3")
server.shutdown()
server.server_close()