JavaTCP網絡編程-最簡單示例 – JAVA編程語言程序開發技術文章

/**
  *TCPServer www.aiwalls.com
  *@author Winty wintys@gmail.com
  *@version 2008-12-15
 */
 import java.io.*;
 import java.net.*;

class TCPServer
{
    public static void main(String[] args)throws IOException
   {
        ServerSocket listen = new ServerSocket(5050);
       
        Socket server  = listen.accept();

        InputStream in = server.getInputStream();
        OutputStream out = server.getOutputStream();

        char c = (char)in.read();
        System.out.println("收到:" + c);

        out.write('s');
       
        out.close();
        in.close();
        server.close();
        listen.close();
    }
}

 
/**
  *TCPClient
  *@author Winty wintys@gmail.com
  *@version 2008-12-15
  */
  import java.io.*;
  import java.net.*;
 
class TCPClient
 {
     public static void main(String[] args)throws IOException
 {
         Socket client = new Socket("127.0.0.1" , 5050);
 
        InputStream in = client.getInputStream();
         OutputStream out = client.getOutputStream();
       
         out.write('c');
 
        char c = (char)in.read();
         System.out.println("收到:" + c);
 
        out.close();
         in.close();
         client.close();
     }
 }
 
 
摘自 奔跑的蝸牛
 

發佈留言