插座

编程入门 行业动态 更新时间:2024-10-26 00:30:05
本文介绍了插座 - 地址已在使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是新来的插座我尝试code对同一应用程序的服务器和客户端只是为了看看它是如何工作的。

I'm new to Socketand I try to code an Server and Client on the same application just to see how it work.

code:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Button)this.findViewById(R.id.bouton1)).setOnClickListener(this); } public void onClick(View v) { TCPServer server = new TCPServer(); TCPClient client = new TCPClient(); server.start(); client.start(); } public class TCPServer extends Thread { @Override public void run() { try { ServerSocket s = new ServerSocket(8080,0,InetAddress.getLocalHost()); Socket cli = s.accept(); byte[] b = new byte[512]; int n; InputStream is = cli.getInputStream(); while((n=is.read(b))>0){ Log.d("TCPServer",new String(b)); if(new String(b).contains("\r\n\r\n"))break; b = new byte[512]; } OutputStream os = cli.getOutputStream(); os.write("Hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } } } public class TCPClient extends Thread { @Override public void run() { try { Socket s = new Socket(InetAddress.getLocalHost().getHostAddress(),8080); //Socket s = new Socket("www.google",80); //Log.i("",s.getLocalAddress().getHostAddress()); byte[] b = new byte[512]; int n; if (s.isConnected()) { OutputStream os = s.getOutputStream(); os.write("Hi How are you \r\n\r\n".getBytes()); InputStream is = s.getInputStream(); while((n=is.read(b))>0){ Log.d("TCPClient",new String(b)); b = new byte[512]; } } s.close(); } catch (Exception e) { e.printStackTrace(); } } }

在code做工精细,但只是在第一次我点击我的按钮。误差 java.BindException:地址已在使用

推荐答案

如果它的工作原理是第一次,但不是以后这听起来像你是不是在程序退出之前正确关闭您的插座。

If it works the first time, but not after that it sounds like you aren't closing your socket correctly before your program exits.

您可以检查它是否仍然是开放的运行

You can check to see if it's still open by running

netstat

等待您不是在Windows机器上。我敢肯定,他们有类似的东西。

pending your not on a windows machine. I'm sure they have something similar.

更多推荐

插座

本文发布于:2023-08-07 03:37:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:插座

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!