使用Java进行网络编程:Socket和HTTP实例

原创 本是古典 何须时尚 2024-10-24 05:33 56阅读 0赞

在网络编程中,Socket是Java中处理TCP连接的API,而HTTP(超文本传输协议)则是一种用于分布式、协作式环境下的应用层通信协议。

以下是一个简单的Socket客户端示例,以及一个基于Apache HttpClient的HTTP客户端示例:

Socket客户端示例:

  1. import java.io.IOException;
  2. import java.net.Socket;
  3. public class SocketClient {
  4. public static void main(String[] args) {
  5. try (Socket socket = new Socket("localhost", 1234))) {
  6. System.out.println("Connected to the server.");
  7. // Send data
  8. byte[] message = "Hello from client!".getBytes();
  9. socket.getOutputStream().write(message);
  10. // Receive data
  11. byte[] receivedMessage = new byte[1024];
  12. socket.getInputStream().read(receivedMessage));
  13. System.out.println("Received message: " + new String(receivedMessage)));
  14. } catch (IOException e) {
  15. e.printStackTrace();
  16. System.out.println("Failed to connect to the server.");
  17. }
  18. }
  19. }

HTTP客户端示例:

  1. import org.apache.http.HttpResponse;
  2. import org.apache.http.client.methods.HttpGet;
  3. public class HttpClientClient {
  4. public static void main(String[] args) {
  5. try {
  6. // Create a http client
  7. HttpClient httpClient = new DefaultHttpClient();
  8. // Execute HTTP GET request
  9. HttpGet httpGet = new HttpGet("http://localhost:1234");
  10. HttpResponse response = httpClient.execute(httpGet);
  11. // Check the response status code (200 for success)
  12. if (response.getStatusLine().getStatusCode() == 200) {
  13. System.out.println("Received message from server:");
  14. // Read and print the response body
  15. String responseBody = EntityUtils.toString(response.getEntity()));
  16. System.out.println(responseBody);
  17. } else {
  18. System.out.println("Failed to retrieve data from server. Status code: " + response.getStatusLine().getStatusCode());
  19. }
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. System.out.println("Failed to connect to the server.");
  23. }
  24. }
  25. }

注意:在生产环境中,你需要处理可能的异常,并且HTTP客户端示例中的URL需要根据实际服务器地址进行修改。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,56人围观)

还没有评论,来说两句吧...

相关阅读