文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Android 开发TCP、UdP客户端

Android 开发TCP、UdP客户端

时间:2011-01-24  来源:fly_binbin

代码一:

 

private void tcpdata() {

try {

Socket s = new Socket("192.168.0.25", 65500);

// outgoing stream redirect to socket

OutputStream out = s.getOutputStream();

// 注意第二个参数据为true将会自动flush,否则需要需要手动操作out.flush()

PrintWriter output = new PrintWriter(out, true);

 

output.println("Hello IdeasAndroid! 伪IP为:"

+ SIMCardToIP("13512345006"));

 

InputStream inputStream = s.getInputStream();

 

DataInputStream input = new DataInputStream(inputStream);

 

byte[] b = new byte[10000];

 

int length = input.read(b);

 

inputReader = new InputStreamReader(inputStream);

 

String Msg = new String(b, 0, length, "gb2312");

 

Toast.makeText(TcpTest.this, Msg, 1000).show();

 

Log.d("Tcp Demo", "message From Server:" + Msg);

s.close();

 

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

下面的代码是UDP通讯的过程: public String send(String msg) { StringBuilder sb = new StringBuilder(); InetAddress local = null; try { local = InetAddress.getByName("192.168.0.25"); // 本机测试 } catch (UnknownHostException e) { e.printStackTrace(); } try { dSocket = new DatagramSocket(); // 注意此处要先在配置文件里设置权限,否则会抛权限不足的异常 } catch (SocketException e) { e.printStackTrace(); } int msg_len = msg == null ? 0 : msg.length(); DatagramPacket dPacket = new DatagramPacket(msg.getBytes(), msg_len, local, SERVER_PORT); try { dSocket.send(dPacket); } catch (IOException e) { e.printStackTrace(); } try { dSocket.receive(dPacket); sb.append(new String(dPacket.getData())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } dSocket.close(); return sb.toString(); }

 

 

 

 

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载