2021-04-18 11:29  阅读(61)
文章分类:Java 基础教程 文章标签:JavaJava 教程
©  原文作者:w3cschool 原文地址:https://www.w3cschool.cn/java/java-network-tcp-server.html

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();
      }
    }
    
点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Java 网络TCP客户端套接字
上一篇
Java TCP服务器
下一篇
Java 网络UDP套接字