socket 서버 라인 시작

1578 단어 socket
여러 클라이언트를 연결할 수 있는 루트를 통해 시작된 socket 노트
테스트 Test

 @Test
	    public void socket3(){
	    	try(ServerSocket s = new ServerSocket(8010);){
	    		while(true){
	    			Socket socket = s.accept();
		    		Runnable r = new socketRunnable(socket);
		    		Thread t = new Thread(r);
		    		t.start();
	    		}
	    	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
	    }

package models;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class socketRunnable implements Runnable {
	Socket incoming;
	
	public socketRunnable(Socket incoming) {
		super();
		this.incoming = incoming;
	}

	@Override
	public void run() {
		try {
			InputStream inStream = incoming.getInputStream();
			OutputStream outputStream = incoming.getOutputStream();
			try(Scanner in = new Scanner(inStream)){
				PrintWriter out = new PrintWriter(outputStream,true);
				out.println("Hello!        ");
				
				boolean done = false;
				
				while(!done && in.hasNextLine()){
					String line = in.nextLine();
					out.println("   :" + line);
					if(line.trim().equals("BYE"))done = true;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				incoming.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}



좋은 웹페이지 즐겨찾기