【发布时间】:2015-07-31 22:20:31
【问题描述】:
我是 android 开发的新手,所以如果需要任何进一步的信息,请询问...我正在尝试使用套接字将坐标发送到服务器,接收查询结果并“Toast”它们。 到现在为止我的活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
new Thread(new ClientThread()).start();
}
...
class ClientThread implements Runnable {
@SuppressWarnings("deprecation")
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void onClickk(View view) {
try {
// Acquire a reference to the system Location Manager
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);............here some more code regarding coordinates. ............
我正在通过套接字写入坐标(以相同的方法):
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
if (lat!=null){
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("lat", lat);
jsonObject.accumulate("lon", lon);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(json);
如何接收服务器发送的数据?我不知道如何使用 InputSteam。
更新:我的服务器。当从应用程序接收到消息时,服务器会尝试在套接字上写入一个字符串。
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
sock.write(la);
});
});
【问题讨论】:
-
服务器使用什么协议?除了http还有什么?
-
我正在使用 java.net.Socket 库。希望这会有所帮助
-
我不是说android app,你的服务器是java程序?
-
不,这是一个expresse应用,nodejs
-
你的代码很好,从套接字获取输入流,将其包装在像 datainputstream 这样的读取器中并读取传入的数据。
标签: android sockets inputstream