我有一个简单的Android应用程序,应该将一些数据发送到我已经通过套接字的服务器,具有给定的IP和端口号。
在我的onCreate()
上,我连接到服务器。这部分有效:
// connect to the server
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
但sendMessage()
不会向套接字发送任何消息,我的服务器上也没有收到任何消息。该功能甚至不显示日志消息,所以我不知道发生了什么。问题是什么?怎么解决?
//TODO send data
clientThread.sendMessage(100);
这是套接字线程类:
class myApp extends Activity{
//....
ClientThread clientThread;
Thread thread;
//....
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
@Override
public void run() {
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
socket = new Socket(serverAddr, SERVERPORT);
Log.i("Hello: Connected","Hello: Connected");
} catch (IOException e) {
e.printStackTrace();
}
}
void sendMessage(int data) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(data);
Log.i("Hello Message sent","Hello sent: "+data+" to: "+ SERVER_IP+":"+SERVERPORT);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我的服务器端接收(Java服务器):
public void run() {
System.out.println("Got a new user!");
InputStream inp;
try {
/* Get Data From Client */
inp = socket.getInputStream();
int data= inp.read();
System.out.println(address+" "+ data);
if (data!=0) {
scoreboard.b1.y+=1;
if (scoreboard.b1.y==scoreboard.MaxValue) {
System.out.println("HELLLOOOOOOO");
scoreboard.updateValue();
}
scoreboard.repaint();
}
} catch (IOException e) {
return;
}
String line;
}
在out.println(data);
之后,你应该打电话给out.flush();
并且您以错误的方式读取数据,如果您想多次读取,应该有缓冲区和while表达式,如this
我在Android应用中使用的发件人选项(PrintWriter
)发送了错误的值。我把它改成了DataOutputStream
并且它有效。
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
out.write(steps);
out.flush();
同样在服务器上,我几乎忘了有一个while(true)
循环来连续接收消息。现在一切正常!