[英]android socket connection stream
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. 我想您不应该尝试创建新的In和Out流-它是在第一个活动中声明和初始化的。 Just call
Connection03Activity.clientSocket.getOutputStream().writeBytes(...)
. 只需调用
Connection03Activity.clientSocket.getOutputStream().writeBytes(...)
。
Offtopic: 无关:
Don't forget to close streams and socket on application close - it will save battery life and traffic. 不要忘记在应用程序关闭时关闭流和套接字-这将节省电池寿命和流量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.