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();
  }
}
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Java 网络TCP客户端套接字》
文章链接:https://zhuji.vsping.com/293790.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。