Socket通信(续)

  socket通信,是通过ip连接通信。

首先,一个服务端应用可以和多个客户端建立通信。我的是android层的应用

  服务端

public class server extends Thread {


public void run() {
ServerSocket s = null;
Socket socket = null;
String shuru = "";
try {


s = new ServerSocket(9999);
while (true) {
PrintWriter out = null;
BufferedReader in = null;
System.out.println(" server  is  start");
StringBuffer buf = new StringBuffer();
socket = s.accept();
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while ((shuru = in.readLine()) != null) {
buf.append(shuru);
if (shuru != null) {
out.println("you can connection");
out.flush();
break;
}
}
System.out.println("+++++++++++++++++++++++++++++" + buf);
out.close();
in.close();
}
// socket.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("----connect " + "---" + " timeout.");
} finally {
try {
s.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}


客户端 :(次客户端可以 有多个)

  public class OwnIPIng extends Thread {


String ip;
String msg;


public OwnIPIng(String Ip, String msg) throws Exception {
this.ip = Ip;
this.msg = msg;
}


public void run() {
PrintWriter out = null;
BufferedReader in = null;
StringBuffer strbuf = new StringBuffer("you can connection");
try {
 
//  while (true) {
Socket socket = new Socket(ip, 9999);// InetAddress.getLocalHost(),10000
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out.println("are you here");
out.flush();

StringBuffer buf = new StringBuffer();

String xing = "";
while ((xing = in.readLine()) != null) {
System.out.println(xing+ "-----------------------------");
buf.append(xing);
if (xing.contentEquals(strbuf.toString())) {
System.out.println(xing+ "xing------------------------");
Editor ed = sp.edit();
ed.putString("ip_val", ip);
ed.putBoolean("isIp", true);
ed.commit();
// 发送消息
Message msg = new Message();
msg.what = findIp;
handler.sendMessage(msg);
break;
}
}
in.close();
out.close();
//  }
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("connect --" + ip + " --timeout.");


}
}
}


因为有特殊需求,所以将服务端和客户端都放入线程中。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值