ServerSocket 简单例题:
packagecom.kaige123.net;/*
*凯哥
*/importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.ServerSocket;importjava.net.Socket;publicclassTest{publicstaticvoidmain(String[] args)throwsException{// 如果都被占用 那就会抛异常// 建立好一个服务端 监听8080端口ServerSocket server =newServerSocket(8080);// 等待客户端来连接服务器Socket socket = server.accept();//代码运行到这句就会卡主 堵塞 等待InputStream input = socket.getInputStream();OutputStream output = socket.getOutputStream();byte[] b =newbyte[1024*5];intlen = input.read(b);String s =newString(b,0, len);System.out.println(s);fin.read(b)s ="hello 你好客户端!!";output.write(s.getBytes());output.close();input.close();socket.close();}}
浏览器输入:http://127.0.0.1:8080,显示结果:hello 你好