Socket系列:同wifi下,两个安卓设备用Socket通信
看效果:Android Socket简单实例效果服务端Project实现网络权限:<uses-permission android:name="android.permission.INTERNET" />布局activity_main.xml代码:<?xml version="1.0" encoding="utf-8"?><L
·
看效果:
Android Socket简单实例效果
-
服务端Project实现
- 网络权限:
<uses-permission android:name="android.permission.INTERNET" />
- 布局
activity_main.xml
代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/et_ip" android:layout_width="match_parent" android:layout_height="wrap_content"> </EditText> <EditText android:id="@+id/et_data" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.java
代码:
public class MainActivity extends AppCompatActivity { private TextView etIP; private EditText etReceiveData; private ServerSocket serverSocket = null; StringBuffer stringBuffer = new StringBuffer(); private InputStream inputStream; public Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 1: etIP.setText(msg.obj.toString()); break; case 2: etReceiveData.setText(msg.obj.toString()); stringBuffer.setLength(0); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etIP = (TextView) findViewById(R.id.et_ip); etReceiveData = (EditText) findViewById(R.id.et_data); receiveData(); } /* 服务器端接收数据 需要注意以下一点: 服务器端应该是多线程的,因为一个服务器可能会有多个客户端连接在服务器上; */ public void receiveData(){ Thread thread = new Thread(){ @Override public void run() { super.run(); /*指明服务器端的端口号*/ try { serverSocket = new ServerSocket(8000); } catch (IOException e) { e.printStackTrace(); } GetIpAddress.getLocalIpAddress(serverSocket); Message ipMessage = handler.obtainMessage(); ipMessage.what = 1; ipMessage.obj = "IP:" + GetIpAddress.getIP() + " PORT: " + GetIpAddress.getPort(); handler.sendMessage(ipMessage); while (true) { Socket socket = null; try { socket = serverSocket.accept(); inputStream = socket.getInputStream(); } catch (IOException e) { e.printStackTrace(); } new ServerThread(socket, inputStream).start(); } } }; thread.start(); } class ServerThread extends Thread{ private Socket socket; private InputStream inputStream; private StringBuffer stringBuffer = MainActivity.this.stringBuffer; public ServerThread(Socket socket,InputStream inputStream){ this.socket = socket; this.inputStream = inputStream; } @Override public void run() { int len; byte[] bytes = new byte[20]; boolean isString = false; try { //在这里需要明白一下什么时候其会等于 -1,其在输入流关闭时才会等于 -1, //并不是数据读完了,再去读才会等于-1,数据读完了,最结果也就是读不到数据为0而已; while ((len = inputStream.read(bytes)) != -1) { for(int i=0; i<len; i++){ if(bytes[i] != '\0'){ stringBuffer.append((char)bytes[i]); }else { isString = true; break; } } if(isString){ Message dataMessage = handler.obtainMessage(); dataMessage.what = 2; dataMessage.obj = stringBuffer; handler.sendMessage(dataMessage); isString = false; } } //当这个异常发生时,说明客户端那边的连接已经断开 } catch (IOException e) { e.printStackTrace(); try { inputStream.close(); socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } /*当按返回键时,关闭相应的socket资源*/ @Override public void onBackPressed() { super.onBackPressed(); try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
- 还需要一个
GetIpAddress.java
public class GetIpAddress { public static String IP; public static int PORT; public static String getIP(){ return IP; } public static int getPort(){ return PORT; } public static void getLocalIpAddress(ServerSocket serverSocket){ try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){ NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ InetAddress inetAddress = enumIpAddr.nextElement(); String mIP = inetAddress.getHostAddress().substring(0, 3); if(mIP.equals("192")){ IP = inetAddress.getHostAddress(); //获取本地IP PORT = serverSocket.getLocalPort(); //获取本地的PORT Log.e("IP",""+IP); Log.e("PORT",""+PORT); } } } } catch (SocketException e) { e.printStackTrace(); } } }
-
客户端代码
- 网络权限
<uses-permission android:name="android.permission.INTERNET" />
- 布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="wrap_content"> <EditText android:id="@+id/et_ip" android:layout_width="250dp" android:layout_height="wrap_content"> </EditText> <Button android:id="@+id/btn_connect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="connect" android:text="Connect" > </Button> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="wrap_content"> <EditText android:id="@+id/et_data" android:layout_width="250dp" android:layout_height="wrap_content"> </EditText> <Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="send" android:text="Send" > </Button> </LinearLayout> </LinearLayout>
- MainActivity代码:
public class MainActivity extends AppCompatActivity { private EditText etIP, etData; private OutputStream outputStream = null; private Socket socket = null; private String ip; private String data; private boolean socketStatus = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etIP = (EditText) findViewById(R.id.et_ip); etData = (EditText) findViewById(R.id.et_data); } public void connect(View view) { ip = etIP.getText().toString(); if (ip == null) { Toast.makeText(MainActivity.this, "please input Server IP", Toast.LENGTH_SHORT).show(); } Thread thread = new Thread() { @Override public void run() { super.run(); if (!socketStatus) { try { socket = new Socket(ip, 8000); if (socket == null) { } else { socketStatus = true; } outputStream = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } } } }; thread.start(); } public void send(View view) { data = etData.getText().toString(); if (data == null) { Toast.makeText(MainActivity.this, "please input Sending Data", Toast.LENGTH_SHORT).show(); } else { //在后面加上 '\0' ,是为了在服务端方便我们去解析; data = data + '\0'; } Thread thread = new Thread() { @Override public void run() { super.run(); if (socketStatus) { try { outputStream.write(data.getBytes()); } catch (IOException e) { e.printStackTrace(); } } } }; thread.start(); } /*当客户端界面返回时,关闭相应的socket资源*/ @Override public void onBackPressed() { super.onBackPressed(); /*关闭相应的资源*/ try { outputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
搞定!!!!
更多推荐
已为社区贡献9条内容
所有评论(0)