socket 服务端线程启动

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/anguea/article/details/66968376
编写的一个通过线程启动的可以连接多个客户端的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();
			}
		}
		
	}
	
}



阅读更多

没有更多推荐了,返回首页