Socket 通信是一種在移動應用中實現實時數據傳輸的技術
import java.io.IOException;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private Socket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
socket = new Socket("your_server_ip", your_server_port);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
socket = new Socket("your_server_ip", your_server_port);
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
public void sendData(String data) {
if (outputStream != null) {
try {
outputStream.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String receiveData() {
if (inputStream != null) {
try {
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
return new String(buffer, 0, bytesRead);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void closeConnection() {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
這些步驟概述了如何在移動應用中實現 Socket 通信。請注意,這里的代碼示例僅用于說明目的,實際實現可能需要根據你的需求進行調整。