gpt4 book ai didi

java - Android Client 和 PC Server 使用套接字通信

转载 作者:行者123 更新时间:2023-11-29 09:14:49 26 4
gpt4 key购买 nike

我在同一台 PC 上的 android 模拟器和服务器 (java) 上运行客户端,并且正在使用套接字编程。下面附上代码。两者都单独运行良好,但实际数据传输没有发生,我无法弄清楚。

服务器端(PC):

import java.net.*;
import java.io.*;

public class Server_tcp {
void run(){
{
try {
System.out.println("In 1st try blck");
try {
System.out.println("In 2nd try blck");
Boolean end = false;
ServerSocket ss = new ServerSocket(4444);
System.out.println("socket created");
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
System.out.println("socket accepted");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
System.out.println("Tcp Example" + "From client: "+st);
output.println("Good bye and thanks for all the fish :)");
s.close();
if (st==null){ end = true; }
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException exp) {
// TODO Auto-generated catch block
exp.printStackTrace();
}
}
}
public static void main(String args[])
{
Server_tcp server = new Server_tcp();
while(true){
server.run();
}
}
}

客户端(安卓):

package com.try3;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

import java.io.*;
import java.net.*;

public class ClientTCPActivity extends Activity {
/** Called when the activity is first created. */

private EditText et;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("Before try net");
trynet();
System.out.println("after try net");
}
public void trynet() {
System.out.println("inside try net");
try {
System.out.println("inside try");
Socket s = new Socket("127.0.0.1",4444);

//outgoing stream redirect to socket
OutputStream out = (OutputStream) et.getContentDescription();

PrintWriter output = new PrintWriter(out);
output.println("Hello Android!");
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));

//read line(s)
String st = input.readLine();
System.out.println(st);

//Close connection
s.close();

System.out.println(" try ");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最佳答案

在 Android 模拟器中,您应该使用 10.0.2.2 而不是 127.0.0.1 来指代您的 PC

我不明白你想在这里做什么。

OutputStream out = (OutputStream) et.getContentDescription();
PrintWriter output = new PrintWriter(out);

你的意思是:

PrintWriter output = new PrintWriter(s.getOutputStream(),true);

??

关于java - Android Client 和 PC Server 使用套接字通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com