那些年的 网络通信之 TCP/IP 传输控制协议 ip 加 端口 ---
/* 一个文本小写转换为大写的小程序,当客户端从键盘录入一串字符串发送到服务端服务端转换为大写返回给客户端 */ import java.io.*; import java.net.*; class TCPServer implements Runnable{ private ServerSocket serverSocket; private Socket socket; private BufferedInputStream bufinpts; private BufferedOutputStream bufoutpts; private byte [] bufin=new byte[1024]; private int len=-1; public static final int PORT=10085; public void run(){ try{ serverSocket=new ServerSocket(PORT); while(true){ socket=serverSocket.accept(); bufinpts=new BufferedInputStream(socket.getInputStream()); bufoutpts=new BufferedOutputStream(socket.getOutputStream()); while((len=bufinpts.read(bufin))!=-1){ if ("over".equalsIgnoreCase(new String(bufin,0,len))) break; System.out.println(new String(bufin,0,len).toUpperCase()); bufoutpts.write(bufin,0,len); bufoutpts.flush(); // 这一步一定要记住,否则数据还只是在缓存区里 } } } catch(Exception e){ e.printStackTrace(); } } } class TCPClient implements Runnable{ Socket socket; BufferedInputStream in; BufferedOutputStream out; int len=-1; byte[] inBuf=new byte[1024]; public void run(){ try{ socket=new Socket("",TCPServer.PORT); out=new BufferedOutputStream(socket.getOutputStream()); while(true){ in=new BufferedInputStream(System.in); while((len=in.read(inBuf))!=-1){ out.write(inBuf,0,len); out.flush(); if("over".equalsIgnoreCase(new String(inBuf,0,len))) break; } // in=socket.getInputStream() } } catch(Exception e){ e.printStackTrace(); } finally{ if(socket!=null) try{ socket.close(); socket=null; } catch(Exception e){ e.printStackTrace(); } } } } class TCPDemo{ public static void main(String []args){ new Thread(new TCPServer()).start(); new Thread(new TCPClient()).start(); } }
如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。