import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.Date;publicclassserver{//设置端口号/publicstaticint portNo=3333;publicstaticvoidmain(String[] args)throws IOException {//初始化serverSocket类ServerSocket s=newServerSocket(portNo);System.out.println("The Server is starting...");//建立socket连接(阻塞,直到有客户端连接)Socket socket=s.accept();//接收数据try{//构造输入流缓存BufferedReader bufReader=newBufferedReader(newInputStreamReader(socket.getInputStream()));PrintWriter out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);String time=newSimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(newDate());while(true){//按行读取输入内容String strLine=bufReader.readLine();//如果收到byebye则退出循环if(strLine.equals("byebye")){break;}System.out.println("In the Server reveived the info: "+strLine);//向客户端发送接收到的数据System.out.println("The server is send the received msg to the client...");out.println("The received msg is: "+strLine+" and The time is:"+time);}}catch(Exception e){e.printStackTrace();}finally{System.out.println("close the Server socket and the io");//关闭socket,断开连接socket.close();s.close();}}}
客户端
import java.io.*; import java.net.*;publicclassclient{/*** @param args*/publicstatic String clientName="laughcry";//设置端口号publicstaticint portNo=3333;publicstaticvoidmain(String[] args)throws IOException {// TODO Auto-generated method stub//设置连接地址类,连接本地,描述使用本socket的ip地址InetAddress addr=InetAddress.getByName("localhost");//初始化socket类Socket socket=newSocket(addr,portNo);try{System.out.println("socket="+socket);//设置io句柄BufferedReader bufReader=newBufferedReader(newInputStreamReader(socket.getInputStream()));PrintWriter out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);//向服务器端发送数据out.println("Hello server ,I am "+clientName);//接受服务器返回的信息String str=bufReader.readLine();System.out.println("The msg from server is: "+str);out.println("byebye");}catch(Exception e){e.printStackTrace();}finally{//关闭连接System.out.println("close the client socket and the io.");socket.close();}}}
本文详细介绍了一种利用 ESP8266 01S 模块构建 Web 服务器的成功实践方案。通过具体的代码示例和详细的步骤说明,帮助读者快速掌握该模块的使用方法。在疫情期间,作者重新审视并研究了这一未被充分利用的模块,最终成功实现了 Web 服务器的功能。本文不仅提供了完整的代码实现,还涵盖了调试过程中遇到的常见问题及其解决方法,为初学者提供了宝贵的参考。 ...
[详细]