2013년 10월 18일 금요일

Socket 예제

Socket 예제
EchoLoopClient.java

//The Echo server is a well-known service that clients can rendezvous with on port 7. 
//RFC 862 에 정의된 양방향 TCP를 보여주는 간단한 프로토콜, 클라이언트는 에코 서버의 7번 포
//트에 소켓을 열고 데이터 전송, 서버는 데이터를 받아서 클라이언트에 되돌려줌

import java.net.*;
import java.io.*;
public class EchoLoopClient {
    public static void main(String [] args) {
        Socket mySocket;
        String hostName, aLine;
        BufferedReader fromSocket, userInput;
        PrintWriter toSocket;
        try {
            if(args.length > 0)    hostName = args[0];
            else                         hostName = "localhost";
            mySocket = new Socket(hostName, 7); 

            fromSocket = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
toSocket = new PrintWriter(mySocket.getOutputStream());
userInput = new BufferedReader(new InputStreamReader(System.in));

while(true) { }
fromSocket.close();
toSocket.close();                            
}
catch(Unk;867에 정의된 간단한 프로토콜, 클라이언트에서 데이타임 서버의 13번 포트에 대한 소켓을 열면
//서버는 사용자에게 시간을 알려준다.
import java.io.*;
import java.net.*nbsp; if (args.length != 2) 
throw new IllegalArgumentException("인자의 수가 다름");

  // 인자로부터 호스트 이름과 포트번호를 얻어냄
  String&nb // 현재, 연결된 정보를 화면에 표시
System.out.println("Connected to " + socket.getInetAddress() + ":"+ socket.getPort());

// 소켓 클래스 객체로부터 InputSemp="";
while((temp=socketIn.readLine())!=null)
System.out.println("DayTime:" + temp);
socketIn.close();
socket.close();
      }
}






----------------------------- FingerClient.java 

// RFC 1288에 정의된 간단한 프로토콜, 
// 클라이언트는 서버의 79번 포트에 연결
// 사용자의 완전한 이름, 언제, 어디서 접속했는지 등을 알려줌
//*간단한 요청
//  클라이언트에서 캐리지리턴/라인피드 를 서버에 보냄
//  현재 서버에 접속한 모든 사용자를 출력
//실행방법 : java FingerClient rama.poly.edu 79
import java.net.*;
import java.io.*;
public class FingerClient {
public final static int DEFAULT_PORT = 79;
public static void main(String[] args) throws Exception {
String hostname = "localhost";
hostname = args[0];

                                Socket socket = null;
try {
socket = new Socket(hostname, DEFAULT_PORT);
Writer out = new OutputStreamWriter(socket.getOutputStream(), "8859_1");
for(int i=1; i<args.length; i++) {
out.write(args[i]+ " ");
}
out.write("\r\n");
out.flush();
socket.shut                   InputStreamReader in = new InputStreamReader(buffer, "8859_1");
int c;
while((c = in.re= '\r' || c == '\n') {
System.out.write(c);
}
}
}
catch(IOException ioe) {
System.out.println(ioe);
}


        &nIOException ioe) {}
}
}
}? 
 
 


댓글 없음:

댓글 쓰기