我正在尝试使用套接字从VB.NET(服务器)向Android(客户端)发送一些命令。我可以将客户端连接到服务器,但我不知道如何接收服务器发送的命令。
以下是我的Android代码的一部分:
public void connect(View v){ //called on button click
SERVER_IP = ip.getText().toString(); //it gets the server's ip from an editText
SERVER_PORT = Integer.parseInt(port.getText().toString()); //and the port too
Toast.makeText(this, "Trying to connect to\n" + SERVER_IP + ":" + SERVER_PORT + "...", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
public void run() {
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVER_PORT); //It establishes the connection with the server
if(socket != null && socket.isConnected()){ //not sure if it is correct
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//Here comes the problem, I don't know what to add...
}
} catch (Exception e) {
}
}
}).start();
}
这是我的VB.NET发送代码的一部分:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
send(TextBox1.text)
End Sub
Private Sub Send(ByVal command)
Dim temp() As Byte = UTF8.GetBytes(command) 'Is UTF8 right to use for that?
stream.Write(temp, 0, temp.Length)
stream.Flush()
End Sub
问题1:我们是UTF8而不是ASCII编码吗?
问题2:如果Android代码想要使用每秒发送命令的计时器,我会在Android代码中更改什么?
感谢。
答案 0 :(得分:0)
要从BufferedReader读取输入,您需要执行与此类似的操作:
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while((line = input.readLine()) != null){
// do something with the input here
}
有关套接字的精彩教程可从文档中的oracle获得:http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
Android上的默认字符集是UTF-8 http://developer.android.com/reference/java/nio/charset/Charset.html,所以不用担心,但你总是可以从服务器向客户端发送一个字节流,然后根据需要对其进行解码。
要接收字节流,您需要执行此操作:
BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
byte[] buffer = new byte[byteCount];
while(input.read(buffer, 0, byteCount) != -1 ){
// do something with the bytes
// for example decode it to string
String decoded = new String(buffer, Charset.forName("UTF-8"));
// keep in mind this string might not be a complete command it's just a decoded byteCount number of bytes
}
如您所见,如果发送字符串而不是字节,则会更容易。
如果你想定期从服务器接收输入,其中一个解决方案是创建一个循环,打开一个套接字,接收输入,处理它,关闭套接字,然后重复,我们你可以保持循环无休止地跑,直到某些命令,如" STOP"收到了。