728x90
반응형

Java에서의 Socket

Java에서는 socket class가 있어서 지원해준다.

  • java.net.Socket

    • client side의 TCP operation을 진행하는 기본적인 class
    • 밑에 함수들은 remote socket으로 connection을 open하는 함수이다
    • 기본 Constructor (생성자들) -> 여기서 host와 port는 remote(서버)의 주소와 portnumber이다. 
    public Socket(String host, int port) throws UnknownHostException,IOException
    public Socket(InetAddress host, int port) throws IOException
    
    try{
    	Socket toOReilly = new Socket("www.oreilly.com",80);
    } catch(UnknownHostException ex){
    	System.err.println(ex);
    } catch(IOException ex){
    	System.err.println(ex);
    }
  • remote와 local을 나누어서 local interface 어떤 것을 connect할지 정할 수도 있다.
public Socket(String host, int port, InetAddress interface, int localPort) throws UnknownHostException,IOException

그럼 위의 경우에는 remote만 적어주는데 local은 어떻게 되는 것일까?

→ OS에서 그냥 자동으로 선택해준다

 

또한, Socket을 만들고 바로 connect하는 것이 아니라, 만들고 나중에 connect할 수 도 있다.

public Socket()
public void connect(SocketAddress endpoint, int timeout) throws IOException

 

  • SocketAddress Class
    • connection endpoint ( remote host )를 나타내는 것을 도와주는 클래스
    • abstract class이고 생성자밖에 없다
    • socket connection정보(IP 주소, port number)를 제공하는 저장소 느낌이다
    • connect 함수를 사용할 수도 있다. 
    • Getter method
public SocketAddress getRemoteSocketAddress()
public SocketAddress getLocalSocketAddress()

  • InetSocketAddress Class
    • SocketAddress의 Subclass

 

Socket을 통해서 정보를 읽어보자

  • InputStream in = socket.getInputStream();

Socket을 통해서 서버에 써보자

  • OutputStream out = socket.getOutputStream();

 

예시 -> 사전

  • dict라는 TCP protocol에 port 2628로 "DEFINE eng-lat gold" 라고 request를 보내면 server는 gold의 의미를 English-to-latin 사전으로 definition을 보내준다.
package Socket;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class DictClient3 {

    public static void main(String[] args){

        String host = "dict.org";
        try{
            Socket soc = new Socket(host,2628);
            OutputStream out = soc.getOutputStream();
            Writer writer = new OutputStreamWriter(out,"UTF-8");
            writer = new BufferedWriter(writer);
            InputStream in = soc.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in,"UTF-8"));
            String request = "DEFINE fd-eng-lat gold";
            writer.write(request);
            writer.flush();
            soc.shutdownOutput();

            for(String line = reader.readLine();line!=null;line=reader.readLine()){
                System.out.println(line);
            }
            soc.close();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

 

 

Socket에 대한 정보 알아오기

Closed or Connected

  • isClosed() 함수는 socket이 닫혀있으면 true를 리턴하고, open되어 있으면 false를 리턴한다.
  • isConnected() 함수는 한번이라도 remote host와 연결되었다면 true를 리턴한다.
  • 만약 socket이 한번도 연결된 적이 없다면 isClosed() 함수는 open되어있지 않더라도 false를 return하게 된다. 
  • 따라서 socket connection이 제대로 open되어있는지 확인하려면 아래와 같이 확인해야 한다.
    • socket.isConnected() && !socket.isClosed()
728x90
반응형

'백엔드 > Network Programming' 카테고리의 다른 글

Non-blocking I/O in Java  (0) 2022.12.12
Socket Programming(3) - Socket for Server  (0) 2022.11.21
Socket Programming(1) - socket이란?  (0) 2022.11.13
URL and URI's key  (2) 2022.10.15
Internet protocols and layers  (2) 2022.09.09

+ Recent posts