package com.thinkgem.wlw.modules.test.socketdemo; import java.io.*; import java.net.Socket; /** * @Author zhouhe * @Date 2019/10/14 17:41 */ public class Client extends Thread{ //定义一个Socket对象 Socket socket = null; private static String host = "192.168.0.109"; private static int port = 777; public Client() { try { //需要服务器的IP地址和端口号,才能获得正确的Socket对象 socket = new Socket(host, port); } catch (Exception e) { } } @Override public void run() { //客户端一连接就可以写数据个服务器了 super.run(); try { // 读Sock里面的数据 InputStream s = socket.getInputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = s.read(buf)) != -1) { System.out.println(new String(buf, 0, len)); } } catch (Exception e) { System.out.println("socket连接断开!"); } } //函数入口 public static void main(String[] args) { //需要服务器的正确的IP地址和端口号 while (true){ Client clientTest = new Client(); clientTest.start(); } } } |