简体   繁体   English

发送和接收TCP套接字android客户端

[英]Send and Receive TCP socket android client

I wrote c# client-server application, server is sending data using socket.send(byte[]) and receive using socket.receive(byte[]) now i want to send and receive from android and totally new to android. 我编写了C#客户端-服务器应用程序,服务器正在使用socket.send(byte [])发送数据,并使用socket.receive(byte [])进行接收,现在我想从android发送和接收,这对android来说是全新的。

i appreciate any kind of help. 我感谢任何形式的帮助。

//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);

You can use a TCP socket and a input stream to read data in a separate thread from the main application thread in your android app like this: 您可以使用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();
}
});

You can wrap the input stream in various other types of stream if you want to read in multibyte values such as shorts or ints (DataInputStream). 如果要读取多字节值,例如短裤或整数(DataInputStream),则可以将输入流包装为其他各种类型的流。 These will take care of converting from network endianess to the native endianess of the client. 这些将负责从网络端到客户端的本地端的转换。

You can get an output stream from the socket to write data back to the server. 您可以从套接字获取输出流,以将数据写回到服务器。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM