package socket;

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

/**
 * @author hanli
 *
 */
public class SocketTest {
	public static void main(String[] args) throws UnknownHostException, IOException {
		try(ServerSocket s = new ServerSocket(8189)) {
			s.setSoTimeout(100);                   //建立一个8189端口的服务器
			
			try (Socket incoming = s.accept()){    //等待客户端连接并接受
				InputStream inStream = incoming.getInputStream();
				OutputStream outStream = incoming.getOutputStream();
				
				try(Scanner in = new Scanner(inStream,"UTF-8")){   //构建一个扫描器,产生从输入流扫描到的值
					PrintWriter out = new PrintWriter(new OutputStreamWriter(outStream,"UTF-8"),true );
					out.print("hello");
					
					boolean done = false;
					
					while (!done && in.hasNextLine()){
						String line = in.nextLine();
						out.print(line);
						
						if(line.trim().equals(" bey ")) 
							done = true;
					}
				}
			}
		}
	}
}

 

版权声明:本文为fanren224原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/fanren224/p/8457168.html