socketサービス側スレッド起動

1576 ワード

スレッドによって起動された複数のクライアントに接続できる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();
			}
		}
		
	}
	
}