zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然 JAVA开发学习:网络编程

    import java.net.*;
    import java.io.*;
     
    public class GreetingClient
    {
       public static void main(String [] args)
       {
          String serverName = args[0];
          int port = Integer.parseInt(args[1]);
          try
          {
             System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
             Socket client = new Socket(serverName, port);
             System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
             OutputStream outToServer = client.getOutputStream();
             DataOutputStream out = new DataOutputStream(outToServer);
     
             out.writeUTF("Hello from " + client.getLocalSocketAddress());
             InputStream inFromServer = client.getInputStream();
             DataInputStream in = new DataInputStream(inFromServer);
             System.out.println("服务器响应: " + in.readUTF());
             client.close();
          }catch(IOException e)
          {
             e.printStackTrace();
          }
       }
    }
    import java.net.*;
    import java.io.*;
     
    public class GreetingServer extends Thread
    {
       private ServerSocket serverSocket;
       
       public GreetingServer(int port) throws IOException
       {
          serverSocket = new ServerSocket(port);
          serverSocket.setSoTimeout(10000);
       }
     
       public void run()
       {
          while(true)
          {
             try
             {
                System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("远程主机地址:" + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "
    Goodbye!");
                server.close();
             }catch(SocketTimeoutException s)
             {
                System.out.println("Socket timed out!");
                break;
             }catch(IOException e)
             {
                e.printStackTrace();
                break;
             }
          }
       }
       public static void main(String [] args)
       {
          int port = Integer.parseInt(args[0]);
          try
          {
             Thread t = new GreetingServer(port);
             t.run();
          }catch(IOException e)
          {
             e.printStackTrace();
          }
       }
    }
  • 相关阅读:
    打印杨辉三角C语言小程序
    奇怪的比赛蓝桥杯
    (转)Silverlight CoreCLR结构浅析
    试一试!
    (转)使用自定义行为扩展 WCF
    分组合并的使用
    多进程,多线程(转载)
    在 ASP.NET 网页中不经过回发而实现客户端回调(需要实现ICallbackEventHandler接口)
    读书笔记
    WCF学习笔记3(客户端内部运行机制分析)
  • 原文地址:https://www.cnblogs.com/tszr/p/10967118.html
Copyright © 2011-2022 走看看