|
MultiThread ¹× SocketÀ» ÀÌ¿ëÇÑ °£´ÜÇÑ Client/Server ÇÁ·Î±×·¥ ÀÔ´Ï´Ù.
¸¸¾à MultiThread·Î ±¸¼ºÀ» ÇÏÁö ¾Ê´Â´Ù¸é read MethodÀÇ BlockingÀ¸·Î ÀÎÇØ ¿©·¯¸íÀÇ Å¬¶óÀÌ¾ðÆ®¿¡ ´ëÇØ 󸮸¦ ÇÏÁö ¸øÇÏ°Ô µÇÁÒ...
ÂüÁ¶Çϼ¼¿ä.
[ MultiThreadEchoServer.java] -- ¼¹öÀÌ´Ï±î ½ÇÇà½Ã Æ÷Æ® ¹øÈ£¸¸ ÀÎÀÚ·Î ÁÖ¼¼¿ä... java MultiThreadEchoServer 1000
import java.io.*; import java.net.*;
class MultiThreadEchoServer extends Thread { protected Socket sock; //----------------------- Constructor MultiThreadEchoServer (Socket sock) { this.sock = sock; }
//------------------------------------ public void run() { try { System.out.println(sock + ": ¿¬°áµÊ"); InputStream fromClient = sock.getInputStream(); OutputStream toClient = sock.getOutputStream(); byte[] buf = new byte[1024]; int count; while( (count = fromClient.read(buf)) != -1 ) { toClient.write( buf, 0, count ); System.out.write(buf, 0, count); } toClient.close(); System.out.println(sock + ": ¿¬°á Á¾·á"); } catch( IOException ex ) { System.out.println(sock + ": ¿¬°á Á¾·á (" + ex + ")"); } finally { try { if ( sock != null ) sock.close(); } catch( IOException ex ) {} } }
//------------------------------------ public static void main( String[] args ) throws IOException { ServerSocket serverSock = new ServerSocket( Integer.parseInt(args[0]) ); System.out.println(serverSock + ": ¼¹ö ¼ÒÄÏ »ý¼º"); while(true) { Socket client = serverSock.accept(); MultiThreadEchoServer myServer = new MultiThreadEchoServer(client); myServer.start(); } } }
Ŭ¶óÀÌ¾ðÆ® ÇÁ·Î±×·¥Àº ÀÌÀü °ÁÂÀÇ EchoClient.java¿Í µ¿ÀÏ ÇÕ´Ï´Ù.
[EchoClient.java] //Ŭ¶óÀÌ¾ðÆ® À̹ǷΠ½ÇÇà½Ã ¼¹ö, Æ÷Å©¹øÈ£ 2°³¸¦ ÀÎÀÚ·Î ÁÝ´Ï´Ù. java EchoClient 1000
import java.io.*; import java.net.*;
class EchoClient { public static void main( String[] args ) throws IOException { Socket sock = null; try { sock = new Socket(args[0], Integer.parseInt(args[1])); System.out.println(sock + ": ¿¬°áµÊ"); OutputStream toServer = sock.getOutputStream(); InputStream fromServer = sock.getInputStream();
byte[] buf = new byte[1024]; int count; while( (count = System.in.read(buf)) != -1 ) { toServer.write( buf, 0, count ); count = fromServer.read( buf ); System.out.write( buf, 0, count ); } toServer.close(); while((count = fromServer.read(buf)) != -1 ) System.out.write( buf, 0, count ); System.out.close(); System.out.println(sock + ": ¿¬°á Á¾·á"); } catch( IOException ex )
{ System.out.println("¿¬°á Á¾·á (" + ex + ")"); } finally { try { if ( sock != null ) sock.close(); } catch( IOException ex ) {} } } }
|