在进行Android开发的过程中,免不了,要开发TCP/UDP通讯的程序,下面这两段代码,分别介绍了TCP/UCP通过的一个实例:
代码一:
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();
}
}