TCP/IP 网络通信基础

时间:2021-12-03 10:17:37

               通过TCP/IP让两台真机进行通信,选定一台真机做服务器,一台做客户端,客户端需要知道服务器端的ip,通过adb命令可以查看到连接到wifi的平板的ip,

              adb shell netcfg

              TCP/IP 网络通信基础

             如图,可以查看到ip为192.168.1.79

             注意一点:android3.0版本以后的网络通信不能在主线程实现,而必须要新建线程去实现,这一点,让我忙了一天没能发现!!!!

              下面是服务器端代码:

               new ServerThread().start();

class ServerThread extends Thread{
public void run(){
ServerSocket serversocket = null;
try {
int length = 0;
char c[] = new char[100];
char t;
serversocket = new ServerSocket(6000);
Socket socket = serversocket.accept();
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
while((t = inputStream.readChar()) != '\n'){
c[length] = t;
System.out.println(c);
length ++;
}
String name = new String(c,0,length) ; 
System.out.println(name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(serversocket != null)
serversocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

需配置<uses-permission android:name="android.permission.INTERNET"></uses-permission>权限,才能创建socket对象

        客户端代码:

        new ClientThread().start();

class ClientThread extends Thread{
public void run(){
Socket socket = null;
socket = new Socket();
InetSocketAddress  isa = new InetSocketAddress(HOST, PORT);
try {
socket.connect(isa, 10000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeChars("hello");
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

也需要配置<uses-permission android:name="android.permission.INTERNET"></uses-permission>权限

         实现结果:

          启动服务器,从客户端中发送hello到服务器,服务器可以收到并显示出来

下周实现服务器收到后返回值给客户端。