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();
			}
		}
		
	}
	
}



你可能感兴趣的:(socket)