Android socket代码无法运行
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread=new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println("Hello World!");
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("启动服务器....");
Socket s = ss.accept();
System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//读取客户端发送来的消息
String mess = br.readLine();
System.out.println("客户端:"+mess);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(mess+"\n");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
以上是一段网上找来的代码,在IntelliJ IDEA下可以正常运行,可以观察到8888端口处于listen
状态。
最近在学习Android编程,用Android Studio把以上代码核心部分复制到MainActivity.java中,然后可以运行,以下为控制台输出内容:
Client not ready yet..Waiting for process to come online
Connected to process 4234 on device Nexus_5X_API_27_x86 [emulator-5554]
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/zygote: Not late-enabling -Xcheck:jni (already on)
W/zygote: Unexpected CPU variant for X86 using defaults: x86
I/InstantRun: starting instant run server: is main process
I/System.out: Hello World!
I/System.out: 启动服务器....
D/OpenGLRenderer: HWUI GL Pipeline
I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0x9d4050c0: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0x9d4050c0: ver 3 1 (tinfo 0x9d403300)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
D/EGL_emulation: eglMakeCurrent: 0x9d4050c0: ver 3 1 (tinfo 0x9d403300)
此时发现8888
端口并没有处于Listen
状态,而且也无法与client
端进行通信。
请问各位,问题可能会出在哪里?多谢了。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之, 举个例子.
假设你在你朋友的手机上运行你的这个程序,监听 8888 端口, 运行一切正常.
现在问题来了: 请问,你电脑上的 8888 端口会处于 Listen 状态吗?
没写IP地址