网络编程2

来源:互联网 发布:工程造价软件破解版 编辑:程序博客网 时间:2024/06/16 15:03
import java.io.*;    import java.net.*;      public class TCPClient {        public static void main(String[] args) throws UnknownHostException, IOException {          // TODO Auto-generated method stub          //创建客户端            Socket client=new Socket(InetAddress.getLocalHost(),8002);            //得到接收数据的流            InputStream is=client.getInputStream();            //将接收到的数据放到缓冲区b            byte[] b=new byte[1024];            int len=is.read(b);            //将缓冲区中的数据输出            System.out.println(new String(b,0,len));            //关闭scoket对象,释放资源          client.close();            }          }  

import java.io.*;  import java.net.*;    public class TCPServer{      public static void main(String[] args) throws Exception{            //创建服务器端,端口号为8002            ServerSocket server=new ServerSocket(8002);            //等待客户端连接            Socket client=server.accept();            //获取客户端的输出流            OutputStream os=client.getOutputStream();                        System.out.println("开始与客户端进行交互");            //向客户端输出数据            os.write(("Hello,world").getBytes());            Thread.sleep(3000);            //结束与客户端的交互            System.out.println("结束与客户端的交互");            //关闭连接            os.close();            client.close();        }        }