login
ȸ¿ø°¡ÀÔ IDPWã±â










home > Á¤º¸¸¶´ç > »çÀ̹ö°­ÀǽÇ
Á¦ ¸ñ [ÀÚ¹Ù±âÃÊÀ¥ÇÁ·¹ÀÓ¿öÅ©]Thread,SocketÀ» ÀÌ¿ëÇÑ Client/Server
±Û¾´ÀÌ webmaster µî·ÏÀÏ 2009-03-31 ÷ºÎ      
³» ¿ë

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 ) {}
}
}
}

¼­¿ï ±¸·Î±¸ ±¸·Îµ¿ 197-10 À̾ؾ¾º¥Ã³µå¸²Å¸¿ö2Â÷ 12Ãþ 1202, 1209È£ (ÁÖ)¿À¿£Á¦À̽ýºÅÛÁî,¿À¶óŬÀÚ¹Ù±³À°Çпø
´ëÇ¥ÀÚ¸í : ÀÌ Á¾ ö | »ç¾÷ÀÚ¹øÈ£ : 107-86-88432 | ÀüÈ­:070-7555-4760~1 | ÆÑ½º :02-837-4760
Åë½ÅÆÇ¸Å¾÷ ½Å°í¹øÈ£ : Á¦2009-¼­¿ï±¸·Î-0447È£
Copyright ¨Ï oraclejava.co.kr All rights reserved.