package com;import java.io.*;import java.net.InetSocketAddress;import java.net.Socket;import java.net.UnknownHostException;public class SocketDemo {public static void main(String[] args) {// 测试Socket连接方法String host = "10.10.100.254";int port = 8899;String request = "GET / HTTP/1.1\r\nHost: 10.10.100.254\r\nConnection: close\r\n\r\n";InetSocketAddress mAddress;System.out.println("正在连接到 " + host + ":" + port);String response = createSocketConnection(host, port, request);System.out.println("服务器响应:\n" + response);}/*** 创建Socket连接并发送请求* @param host 服务器主机名或IP地址* @param port 服务器端口号* @param request 要发送的请求数据* @return 服务器响应数据*/public static String createSocketConnection(String host, int port, String request) {Socket socket = null;BufferedReader in = null;PrintWriter out = null;StringBuilder response = new StringBuilder();try {System.out.println("Socket连接: " );// 创建Socket连接socket = new Socket(host, port);System.out.println("Socket连接成功: " + socket);// 获取输出流,用于向服务器发送数据out = new PrintWriter(socket.getOutputStream(), true);// 获取输入流,用于读取服务器响应in = new BufferedReader(new InputStreamReader(socket.getInputStream()));// 发送请求out.println(request);// 读取响应String line;while ((line = in.readLine()) != null) {response.append(line).append("\n");}} catch (UnknownHostException e) {System.err.println("无法解析主机: " + host);e.printStackTrace();} catch (IOException e) {System.err.println("IO错误: " + e.getMessage());e.printStackTrace();} finally {// 关闭资源try {if (in != null) in.close();if (out != null) out.close();if (socket != null) socket.close();System.out.println("Socket连接已关闭");} catch (IOException e) {System.err.println("关闭资源时出错: " + e.getMessage());}}return response.toString();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。