简单socket服务器编程
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; } } } } } }