I use Socket to connect to my local server:
public static Socket clientSocket;
public static DataOutputStream outToServer;
public static DataInputStream inToServer;
...
clientSocket = new Socket("192.168.1.102", 15780);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inToServer = new DataInputStream(clientSocket.getInputStream());
outToServer.writeBytes(nameStr + "\n");
outToServer.flush();
it works but if I check username and go to next Activity
Intent i = new Intent(this, RoomClass.class);
startActivity(i);
i can't use (connection is always open)
outToServer = new DataOutputStream(Connection03Activity.clientSocket.getOutputStream());
inToServer = new DataInputStream(Connection03Activity.clientSocket.getInputStream());
outToServer.writeBytes(str + "\n");
outToServer.flush();
why? how to organize connection rigth?
I suppose you should not try to create new In and Out streams - it was declared and initialized in first activity. Just call Connection03Activity.clientSocket.getOutputStream().writeBytes(...)
.
Offtopic:
Don't forget to close streams and socket on application close - it will save battery life and traffic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.