当前位置: 首页 > article >正文

第三百二十八节 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();
  }
}


http://www.kler.cn/a/407324.html

相关文章:

  • PLC的指令全集1+TIA PORTAL仿真(西门子S7 1200)
  • 浮点数的表示—IEEE754标准
  • c#:winform引入bartender
  • 【大数据技术基础】 课程 第5章 HBase的安装和基础编程 大数据基础编程、实验和案例教程(第2版)
  • Windows之使用putty软件以ssh的方式连接Linux中文显示乱码
  • Django+Nginx+uwsgi网站使用Channels+redis+daphne实现简单的多人在线聊天及消息存储功能
  • 大疆上云api开发
  • /etc/sudoers 文件格式解读
  • VM虚拟机装MAC后无法联网,如何解决?
  • 飞凌嵌入式旗下教育品牌ElfBoard与西安科技大学共建「科教融合基地」
  • android 性能分析工具(03)Android Studio Profiler及常见性能图表解读
  • 绝世唐门:雨浩黑发泪痣形象,王东无新建模,动画漫画对比凸显
  • 百度在下一盘大棋
  • 简述C++STL-队列
  • PHP 二分法查找算法
  • React.memo 的使用
  • [Redis#4] string | 常用命令 | + mysql use:cache | session
  • 摄影:相机控色
  • Linux系统Docker部署开源在线协作笔记Trilium Notes与远程访问详细教程
  • 【笔记】自动驾驶预测与决策规划_Part7_数据驱动的预测方法