我正在尝试使用 python 中的套接字(我的电脑)创建一个简单的聊天服务器程序来与我的 Android 客户端代码(我的 Android 手机)通信。
我有一个简单的服务器代码,它可以接收消息,但是当我尝试从服务器向客户端发送消息时,它会阻止客户端应用程序并崩溃。
客户端代码基于本教程:Simple Android Chat Application, client side.
客户端代码:
private class ChatClientThread extends Thread {
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
@Override
public void run() {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(name);
dataOutputStream.flush();
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog += dataInputStream.readUTF();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
chatMsg.setText(msgLog);
}
});
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
loginPanel.setVisibility(View.VISIBLE);
chatPanel.setVisibility(View.GONE);
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
服务器代码:
import socket
s = socket.socket()
host = "192.168.1.82"
port = 8080
s.bind((host, port))
print host
s.listen(5)
c = None
while True:
if c is None:
# Halts
print '[Waiting for connection...]'
c, addr = s.accept()
print 'Got connection from', addr
else:
# Halts
print '[Waiting for response...]'
print c.recv(1024)
当添加下面两行发送消息时,它不起作用。
# Halts
print '[Waiting for response...]'
print c.recv(1024)
q = raw_input() c.send(q)
关于如何修复它有什么想法吗?
请您参考如下方法:
DataOutput.writeUTF()和 DataInput.readUTF() Java 中的方法在 Python 中没有任何直接等价物。作为 DataOutput.writeUTF() 的 Javadocs状态:
Writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every character in the string s. If s is null, a NullPointerException is thrown. Each character in the string s is converted to a group of one, two, or three bytes, depending on the value of the character.
两个长度字节是大端顺序。因此,至少,python 程序读取此信息必须首先读取这两个长度字节以确定后续数据的长度,然后读取那么多字节的特殊编码字符数据,最后对其进行解码。根据讨论 here,在 python 端解码它似乎很重要关于使用的编码,称为“修改后的 UTF-8”:
The differences between this format and the standard UTF-8 format are the following:
- The null byte '\u0000' is encoded in 2-byte format rather than 1-byte, so that the encoded strings never have embedded nulls.
- Only the 1-byte, 2-byte, and 3-byte formats are used.
- Supplementary characters are represented in the form of surrogate pairs.
作为替代方案,我认为会容易得多,在 Java 方面考虑放弃 readUTf() 和 writeUTF() 方法并用您自己的版本替换它们像下面这样:
public void writeUTF8(String s, DataOutput out) throws IOException {
byte [] encoded = s.getBytes(StandardCharsets.UTF_8);
out.writeInt(encoded.length);
out.write(encoded);
}
public String readUTF8(DataInput in) throws IOException {
int length = in.readInt();
byte [] encoded = new byte[length];
in.readFully(encoded);
return new String(encoded, StandardCharsets.UTF_8);
}
然后,在 python 端,等效代码可能是:
def recvall(sock, size):
received_chunks = []
buf_size = 4096
remaining = size
while remaining > 0:
received = sock.recv(min(remaining, buf_size))
if not received:
raise Exception('unexcepted EOF')
received_chunks.append(received)
remaining -= len(received)
return b''.join(received_chunks)
def read_utf8(sock):
len_bytes = recvall(sock, 4)
length = struct.unpack('>i', len_bytes)[0]
encoded = recvall(sock, length)
return str(encoded, encoding='utf-8')
def write_utf8(s: str, sock: socket.socket):
encoded = s.encode(encoding='utf-8')
sock.sendall(struct.pack('>i', len(encoded)))
sock.sendall(encoded)
