Wu Yuxiong - natural born JAVA development of learning: Network Programming

Import the java.net *. ;
 Import the java.io. * ; 
 
public  class GreetingClient 
{ 
   public  static  void main (String [] args) 
   { 
      String the serverName = args [0 ];
       int Port = the Integer.parseInt (args [. 1 ]);
       the try 
      { 
         System.out.println ( "connected to the host:" + serverName + ", the port number:" + port); 
         the Socket Client = new new the Socket (the serverName, port); 
         System.out.println ( "remote host address:" + 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 ( "waiting for a remote connection, port number:" serverSocket.getLocalPort + () + "..." ); 
            the Socket Server = serverSocket.accept (); 
            System.out.println ( "remote host address: "+ server.getRemoteSocketAddress ()); 
            DataInputStream in = new new DataInputStream (server.getInputStream ()); 
            System.out.println (in.readUTF ()); 
            the DataOutputStream OUT = new new the DataOutputStream (server.getOutputStream ()); 
            OUT. writeUTF ( "I thank connection:" + server.getLocalSocketAddress () + "! \ nGoodbye" ); 
            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 (); 
      } 
   } 
}

 

Guess you like

Origin www.cnblogs.com/tszr/p/10967118.html