Android套接字接收数据
Android socket receive data
我是 android 开发的新手,所以如果需要任何进一步的信息,请询问...我正在尝试使用套接字将坐标发送到服务器,接收查询结果和 "Toast" 它们。
直到现在在我的 activity:
@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);
});
});
class Client extends Thread {
public void run()
{
try
{
Socket socket = new Socket(address, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(json);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = in.readLine()
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
socket.close();
}
catch(Exception e) {}
}
}
我遇到了类似的问题,最后在这里找到:
MainActivity.java
public class MainActivity extends AppCompatActivity {
// private ListView mList;
// private ArrayList<String> arrayList;
// private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.connectBtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// connect to the server
TCPClient.buttonPushed = "Kamran Gasimov, hi";
new connectTask().execute("");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
@Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
Log.d("Message", message);
}
});
mTcpClient.run();
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("values", values[0]);
//in the arrayList we add the messaged received from server
// arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
// mAdapter.notifyDataSetChanged();
}
}
}
TCPClient.java
public class TCPClient {
private String serverMessage;
public static String buttonPushed;
public static final String SERVERIP = "192.168.1.100"; //your Photon (formerly computer) IP address
public static final int SERVERPORT = 7777;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedWriter out1;
OutputStreamWriter out2;
OutputStream out3;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* @param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
Log.d("TCP Client", "Message: " + message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out3 = socket.getOutputStream();
out2 = new OutputStreamWriter(socket.getOutputStream());
out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: out3 = " + out3);
Log.e("TCP Client", "C: out2 = " + out2);
Log.e("TCP Client", "C: out1 = " + out1);
Log.e("TCP Client", "C: out0 = " + out);
sendMessage(buttonPushed); //this was the key
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.e("TCP Client", "C: received = " + in);
Log.e("TCP Client", "C: run = " + mRun);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.e("TCP Client", "C: I got to the while loop!");
serverMessage = in.readLine();
Log.e("TCP Client", "C: serverMessage = " + serverMessage);
new TCPClient(mMessageListener);
stopClient();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
} else {
serverMessage = null;
}
}
Log.e("TCP Client", "C: run = " + mRun);
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
Log.d("TCP Client", "Socket closed.");
serverMessage = null;
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
我是 android 开发的新手,所以如果需要任何进一步的信息,请询问...我正在尝试使用套接字将坐标发送到服务器,接收查询结果和 "Toast" 它们。 直到现在在我的 activity:
@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);
});
});
class Client extends Thread {
public void run()
{
try
{
Socket socket = new Socket(address, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(json);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = in.readLine()
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
socket.close();
}
catch(Exception e) {}
}
}
我遇到了类似的问题,最后在这里找到:
MainActivity.java
public class MainActivity extends AppCompatActivity {
// private ListView mList;
// private ArrayList<String> arrayList;
// private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.connectBtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// connect to the server
TCPClient.buttonPushed = "Kamran Gasimov, hi";
new connectTask().execute("");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
@Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
@Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
Log.d("Message", message);
}
});
mTcpClient.run();
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("values", values[0]);
//in the arrayList we add the messaged received from server
// arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
// mAdapter.notifyDataSetChanged();
}
}
}
TCPClient.java
public class TCPClient {
private String serverMessage;
public static String buttonPushed;
public static final String SERVERIP = "192.168.1.100"; //your Photon (formerly computer) IP address
public static final int SERVERPORT = 7777;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedWriter out1;
OutputStreamWriter out2;
OutputStream out3;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public TCPClient(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* @param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
Log.d("TCP Client", "Message: " + message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out3 = socket.getOutputStream();
out2 = new OutputStreamWriter(socket.getOutputStream());
out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: out3 = " + out3);
Log.e("TCP Client", "C: out2 = " + out2);
Log.e("TCP Client", "C: out1 = " + out1);
Log.e("TCP Client", "C: out0 = " + out);
sendMessage(buttonPushed); //this was the key
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.e("TCP Client", "C: received = " + in);
Log.e("TCP Client", "C: run = " + mRun);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.e("TCP Client", "C: I got to the while loop!");
serverMessage = in.readLine();
Log.e("TCP Client", "C: serverMessage = " + serverMessage);
new TCPClient(mMessageListener);
stopClient();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
} else {
serverMessage = null;
}
}
Log.e("TCP Client", "C: run = " + mRun);
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//the socket must be closed. It is not possible to reconnect to this socket
// after it is closed, which means a new socket instance has to be created.
socket.close();
Log.d("TCP Client", "Socket closed.");
serverMessage = null;
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}