Android Socket编程与客户端通信
云服务器
环境
Android Studio
JDK 14
阿里云服务器
Android客户端
activity_main.xml
src/main/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Socket"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
src/main/res/layout/activity_main.xml
package com.demo.socket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final String host_name = this.getString(R.string.host_name);
final int port = Integer.parseInt(this.getString(R.string.port));
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
Socket socket = null;
try {
OutputStream outputStream = socket.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeUTF("Hello World!");
InputStream inFromServer = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inFromServer);
System.out.println("Server response: " + dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
});
}
}
AndroidManifest.xml
src/main/AndroidManifest.xml
添加下列语句以授权互联网访问权限
<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.socket">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
strings.xml
src/main/res/values/strings.xml
其中<host_name>
为服务器公网IP,<port>
为端口号,需与服务器端设置的端口号一致
<resources>
<string name="app_name">Socket</string>
<string name="host_name"><host_name></string>
<string name="port"><port></string>
</resources>
服务器端
其中<port>
为端口号,需与客户端一致
import java.net.*;
import java.io.*;
public class Server {
private static ServerSocket serverSocket;
public static void main(String[] args) {
int port = <port>;
new Thread() {
@Override
public void run() {
System.out.println("Waiting to connect...");
try {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
} catch(SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
Socket server = null;
try {
server = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(server.getInputStream());
System.out.println("Receive " + dataInputStream.readUTF());
DataOutputStream dataOutputStream = new DataOutputStream(server.getOutputStream());
dataOutputStream.writeUTF("Receive successfully!");
} catch (SocketTimeoutException e) {
System.out.println("Time out!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
测试结果
客户端
- UI界面
- logcat
服务器端
云服务器
使用阿里云、腾讯云服务器需要到对应云服务器安全组开放对应的端口,允许请求IP访问
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!