【发布时间】:2011-10-17 21:08:49
【问题描述】:
我编写了 c# 客户端-服务器应用程序,服务器使用 socket.send(byte[]) 发送数据并使用 socket.receive(byte[]) 接收现在我想从 android 发送和接收,对 android 来说是全新的。
感谢任何形式的帮助。
【问题讨论】:
我编写了 c# 客户端-服务器应用程序,服务器使用 socket.send(byte[]) 发送数据并使用 socket.receive(byte[]) 接收现在我想从 android 发送和接收,对 android 来说是全新的。
感谢任何形式的帮助。
【问题讨论】:
//client side
Socket sendChannel=new Socket("localhost", 12345);
OutputStream writer=sendChannel.getOutputStream();
writer.write(new byte[]{1});
writer.flush();
InputStream reader=sendChannel.getInputStream();
byte array[]=new byte[1];
int i=reader.read(array);
//server side
ServerSocket s=new ServerSocket(12345);
Socket receiveChannel = s.accept();
OutputStream writerServer=receiveChannel.getOutputStream();
writer.write(new byte[]{1});
writer.flush();
InputStream readerServer=receiveChannel.getInputStream();
byte array2[]=new byte[1];
int i2=reader.read(array);
【讨论】:
您可以使用 TCP 套接字和输入流在与 Android 应用程序的主应用程序线程不同的线程中读取数据,如下所示:
// Start a thread
new Thread(new Runnable() {
@Override
public void run() {
// Open a socket to the server
Socket socket = new Socket("192.168.1.1", 80);
// Get the stream from which to read data from
// the server
InputStream is = socket.getInputStream();
// Buffer the input stream
BufferedInputStream bis = new BufferedInputStream(is);
// Create a buffer in which to store the data
byte[] buffer = new byte[1024];
// Read in 8 bytes into the first 8 bytes in buffer
int countBytesRead = bis.read(buffer, 0, 8);
// Do something with the data
// Get the output stream from the socket to write data back to the server
OutputStream os = socket.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
// Write the same 8 bytes at the beginning of the buffer back to the server
bos.write(buffer, 0, 8);
// Flush the data in the socket to the server
bos.flush();
// Close the socket
socket.close();
}
});
如果您想读取多字节值,例如 short 或 ints (DataInputStream),您可以将输入流包装在各种其他类型的流中。这些将负责从网络字节序转换为客户端的本地字节序。
您可以从套接字中获取输出流,以将数据写回服务器。
希望这会有所帮助。
【讨论】: