我寫了c#客戶端服務器應用程序,服務器使用socket.send(byte [])發送數據並使用socket.receive(byte [])接收現在我想要發送和接收的數據android和全新的android。發送和接收TCP套接字android客戶端
我欣賞任何形式的幫助。
我寫了c#客戶端服務器應用程序,服務器使用socket.send(byte [])發送數據並使用socket.receive(byte [])接收現在我想要發送和接收的數據android和全新的android。發送和接收TCP套接字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();
}
});
可以在包裝輸入流各種其他類型的流,如果您想讀取多字節值(如短語或整數(DataInputStream))。這些將從網絡永恆性轉變爲客戶端的本地永久性。
您可以從套接字獲取輸出流以將數據寫回服務器。
希望這會有所幫助。