我想在我的java服务器中创建一个printwriter,在我的android代码中创建一个buffertreader。对,知道我可以从我的android发送一条消息并在我的java编译器上阅读它,但我也想做对手。在Android上阅读并在服务器上写。我需要两个应用程序,因为我不知道我是否可以把它放在两个代码之间尝试?
android代码:
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
java服务器:
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
感谢您抽出宝贵时间阅读我的问题
答案 0 :(得分:0)
是的,您可以在它们之间创建双向通信,您只需要在客户端(Android)上打开一个InputStream并在Java Server Side上打开一个OutputStream,它可以通过以下方式实现:
android代码:
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
InputStream in = client.getInputStream();
byte data[] = new byte[1024]
in.read(data); ///perform your reading operation here
client.close(); //closing the connection
} catch (UnknownHostException e) {
java服务器:
while (true) {
try {
clientSocket = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
pw.write(new String("write data here"));
pw.flush();
pw.close();
clientSocket.close();
} catch (IOException ex) {