自学内容网 自学内容网

第三百二十八节 Java网络教程 - Java网络TCP客户端套接字

Java网络教程 - Java网络TCP客户端套接字

Socket 类表示一个TCP客户端套接字。

以下代码显示如何创建TCP客户端套接字:

// Create Socket for 192.168.1.2 at  port 1234
Socket   socket = new Socket("192.168.1.2", 1234);

以下代码显示如何创建未绑定的客户端套接字,绑定它并连接它。

Socket socket = new Socket();
socket.bind(new InetSocketAddress("localhost",  1234));
socket.connect(new InetSocketAddress("localhost",  1234));

在连接Socket对象之后,我们可以分别使用getInputStream()和getOutputStream()方法使用其输入和输出流。

例子

以下代码显示了基于TCP套接字的Echo客户端。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Main {
  public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 12900);
    System.out.println("Started client  socket at "
        + socket.getLocalSocketAddress());
    BufferedReader socketReader = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
    BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(
        socket.getOutputStream()));
    BufferedReader consoleReader = new BufferedReader(
        new InputStreamReader(System.in));

    String promptMsg = "Please enter a  message  (Bye  to quit):";
    String outMsg = null;

    System.out.print(promptMsg);
    while ((outMsg = consoleReader.readLine()) != null) {
      if (outMsg.equalsIgnoreCase("bye")) {
        break;
      }
      // Add a new line to the message to the server,
      // because the server reads one line at a time.
      socketWriter.write(outMsg);
      socketWriter.write("\n");
      socketWriter.flush();

      // Read and display the message from the server
      String inMsg = socketReader.readLine();
      System.out.println("Server: " + inMsg);
      System.out.println(); // Print a blank line
      System.out.print(promptMsg);
    }
    socket.close();
  }
}


原文地址:https://blog.csdn.net/2301_78772942/article/details/143905306

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!