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!

  • 相关阅读:
    test
    VS dll 引用依赖
    Git配置
    编码--文字输入的前因后果
    base64相关
    异或
    UNION / UNION ALL 区别
    数据库使用规范
    chrome插件开发学习(一)
    缓存穿透 缓存雪崩 缓存并发
  • 原文地址:https://www.cnblogs.com/hnrainll/p/2290741.html
Copyright © 2011-2022 走看看