상세 컨텐츠

본문 제목

[JAVA] 임의로 Socketexception 발생시키기

JAVA\Spring

by 박집실 2022. 11. 17. 00:54

본문

package LetChat.cpnt.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SubProxy {

    static ServerSocket serverSocket;
    static Socket socket;
    static Thread thread;

    public static void main(String[] args) {
        try {
            new SubProxy().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void start() throws IOException {
        serverSocket = new ServerSocket(5656);
        while (true) {
            socket = serverSocket.accept();

            thread = new thread(socket);
            thread.start();
        }
    }

}
 class thread extends Thread {
    Socket socket;
    DataOutputStream out;
    DataInputStream in;

    thread(Socket socket) {
        this.socket = socket;
        try {
            this.out = new DataOutputStream(socket.getOutputStream());
            this.in = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {

        try {
            while(true) {
                String str = in.readUTF();
            }
        } catch (IOException e) {
            try {
                SubProxy.serverSocket.close();
                SubProxy.thread.stop();
                throw new RuntimeException(e);
            } catch (Exception je){}
        }

    }
}

in.readUTF()를 이용해서 임의로 소켓이셉션을 발동시킬 수 있음.

또 serverSocket이 안 닫혀서 문제가 자주 발생하니 socket를 닫기 보다는 serverSocket.close()를 하였는지 안 하였는지 확인 잘하도록 하자.

 

 

++ 추가

Datainputstream을 제외한 inputstream 관련 작업에서 새로 Thread 를 생성하여 사용해야함. 안 그럼 각종 exception을 볼 수 있음

 

ㅇㅇ..

관련글 더보기