zoukankan      html  css  js  c++  java
  • Java Socket例程1

    HelloServer.java

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class HelloServer{
    public static void main(String args[]) throws IOException{
    ServerSocket serversocket = null;
    PrintWriter out = null;
    try{
    serversocket = new ServerSocket(9999);
    }
    catch(IOException e)
    {
    System.err.println("Could not listen on port:9999");
    System.exit(1);
    }

    Socket clientsocket = null;
    try{
    clientsocket = serversocket.accept();
    }
    catch(IOException e)
    {
    System.err.println("Accept failed.");
    System.exit(1);
    }
    out = new PrintWriter(clientsocket.getOutputStream(),true);
    out.println("hello world");
    clientsocket.close();
    serversocket.close();
    }
    }

    HelloClient.java

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.net.UnknownHostException;

    public class HelloClient{
    public static void main(String args[]) throws IOException{
    Socket hellosocket = null;
    BufferedReader in = null;
    try{
    hellosocket = new Socket("localhost",9999);
    in = new BufferedReader(new InputStreamReader(hellosocket.getInputStream()));
    }
    catch(UnknownHostException e){
    System.err.println("Don't know about host:localhost");
    System.exit(1);
    }
    catch(IOException e)
    {
    System.err.println("Count't get I/O for the connection.");
    System.exit(1);
    }
    System.out.println(in.readLine());
    in.close();
    hellosocket.close();
    }
    }


    实现功能:先启动服务器,再启动客户端.连接成功之后,服务器给向客户端发送Hello World!

  • 相关阅读:
    jmeter基础介绍
    mysql图形化工具navicat
    JMeter 进行压力测试
    windows ADB配置java adk / Android adk
    性能指标
    压力测试和负载测试(tps/qps)专项测试,吞吐量
    接口测试工具Postman
    charles步骤装
    Python列表操作
    Python字符串常见操作
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2290741.html
Copyright © 2011-2022 走看看