我正在尝试创建一个行为类似于客户端的Android应用程序,我面临的问题是,当从服务器接收字符串数据时,应用程序仅首次接收它。当我重新连接套接字时,应用程序会再次接收数据。
我使用套接字协议应用作为服务器,我在消息的末尾发送一个新的行字符,甚至连接都是活动的,因为我可以将数据发送回服务器。
这是代码
public class MainActivity extends AppCompatActivity {
Thread m_thread;
Socket clientSocket;
PrintWriter out;
boolean fan=false,socket=false,light1=false,light2=false,m_run=false;
int quantity = 0;
String msg;
BufferedReader in = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Start(View view) {
m_thread = new Thread(new Runnable() {
@Override
public void run() {
m_run = true;
try {
clientSocket = new Socket("192.168.1.34", 2001);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
out.println("Client Connected");
out.flush();
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
TextView srv_message = (TextView) findViewById(R.id.messageTextView);
while(m_run)
{
if(msg!=null)
{
srv_message.setText(""+msg);
}
msg = null;
}
}catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
m_thread.start();
}
单击创建连接按钮时调用Start方法。
答案 0 :(得分:1)
使用此代码,它也适用于我。
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (!Thread.currentThread().isInterrupted())
{
try
{
read = input.readLine();
if (read != null) {
// take a handler to Toast the message
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
答案 1 :(得分:0)
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
srv_message.setText(""+result);