服务器端代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
// 创建服务器端的Socket,监听指定端口
serverSocket = new ServerSocket(12345);
System.out.println("Server is listening on port 12345...");
while (true) {
// 等待客户端连接
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
// 处理客户端连接
handleClient(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void handleClient(Socket clientSocket) {
try {
// 获取输入流和输出流
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
// 读取客户端发送的数据
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String receivedData = new String(buffer, 0, bytesRead);
System.out.println("Received from client: " + receivedData);
// 发送响应给客户端
String responseData = "Hello, Client!";
outputStream.write(responseData.getBytes());
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭与客户端的连接
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
try {
// 创建客户端的Socket,连接服务器端
socket = new Socket("localhost", 12345);
System.out.println("Connected to server...");
// 获取输入流和输出流
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 发送数据给服务器
String requestData = "Hello, Server!";
outputStream.write(requestData.getBytes());
outputStream.flush();
// 读取服务器的响应
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String responseData = new String(buffer, 0, bytesRead);
System.out.println("Received from server: " + responseData);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭与服务器的连接
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这个简单的示例演示了一个基于TCP协议的Socket通信过程。在实际应用中,你可能需要考虑更多的异常处理、线程管理、协议设计等方面的问题。请注意,在Android中使用Socket时,要确保网络操作在独立线程中执行,以避免主线程阻塞。
转载请注明出处:http://www.zyzy.cn/article/detail/15207/Android