我的代码是一个信使,通过WiFi将消息从Android设备发送到另一个Android设备。
这是我的代码,在这个课程中我发送消息:
public class ClientThread extends Thread {
String address;
String message;
int portNum;
InetAddress serverAddr;
Socket socket;
PrintWriter out;
boolean broadcast;
public ClientThread(String addr, int port, String msg, boolean bcast) throws IOException {
address = addr;
portNum = port;
message = msg;
broadcast = bcast;
}
public void run() {
try {
ChatService.portsocket.setBroadcast(broadcast);
// Charset.forName("UTF-8").encode(message);
// Log.d("client",new String(message.getBytes()));
// byte[] b = EncodingUtils.getBytes(message,
// Charset.forName("UTF-8").name());
DatagramPacket packet1 = new DatagramPacket(message.getBytes(), message.length(),
InetAddress.getByName(address), 5555);
ChatService.portsocket.send(packet1);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
在本课程中我收到了以下信息:
public class ChatService extends Service {
public static String serverIP;
public static int serverPort = 5555;
private ServerSocket serverSocket;
private serverThread sThread;
public static final String BROADCAST_ACTION = "UpdateEvent";
public static DatagramSocket portsocket;
Intent intent;
int i = 0;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
private class serverThread extends Thread {
public void run() {
try {
serverIP = getLocalIpAddress();
Log.v("addr", serverIP);
if (serverIP != null) {
serverSocket = new ServerSocket(serverPort);
Log.v("socket", "created");
while (true) {
/*
* Socket client = serverSocket.accept();
* Log.v("client", "received");
*/
try {
byte [] buf = new byte [1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ChatService.portsocket.receive(packet);
byte [] result = new byte [packet.getLength()];
System.arraycopy(packet.getData(), 0, result, 0, packet.getLength());
String msg = new String(result);
Log.d("armin", msg);
updateGui(msg, packet.getAddress());
}
catch (Exception e) {
}
}
}
}
catch (Exception e) {
}
}
}
}
当我输入例如آرمین并发送它时,应用程序收到的消息是一个不连贯的单词,例如آر 有人有想法解决它吗?
答案 0 :(得分:1)
如果你有
String message = ...;
将其转换为byte []
byte[] bytes = message.getBytes();
然后必须使用
构造DatagramPacketnew DatagramPacket(bytes, bytes.length(), ... );
您的通话使用
new DatagramPacket( message.getBytes, message.length(),..,
但是这会使用String长度,但是Farsi每个字符需要多个字节。
字符串آرمین有5个字符,但UTF-8编码需要10个字节。你需要发送10个字节。