浅谈java的TCP和UDP编程(附实例讲解)
TCP
客户端:
importjava.io.BufferedReader; importjava.io.InputStreamReader; importjava.io.PrintWriter; importjava.net.Socket; publicclassMyClient{ publicstaticvoidmain(String[]args)throwsException{ Socketsocket=null; BufferedReaderin=null; PrintWriterout=null; BufferedReaderinput=null; //请求指定ip和端口号的服务器 socket=newSocket("127.0.0.1",3333); while(true){ in=newBufferedReader(newInputStreamReader(socket.getInputStream())); out=newPrintWriter(socket.getOutputStream(),true); //接收控制台的输入 input=newBufferedReader(newInputStreamReader(System.in)); //out.println("thisisclientinfo!"); Stringinfo=input.readLine(); out.println(info); Stringstr=in.readLine(); System.out.println("客户端显示--》服务器的信息:"+str); } //in.close(); //out.close(); } }
服务端:
importjava.io.BufferedReader; importjava.io.InputStreamReader; importjava.io.PrintWriter; importjava.net.ServerSocket; importjava.net.Socket; publicclassMyServices{ publicstaticvoidmain(String[]args)throwsException{ ServerSocketss=null; Socketsocket=null; BufferedReaderin=null; PrintWriterout=null; BufferedReaderinput=null; //监听3333端口 ss=newServerSocket(3333); //等待接收客户端的请求 socket=ss.accept(); while(true){ //获取连接对象的输入流 in=newBufferedReader(newInputStreamReader(socket.getInputStream())); //获取客户端的输入信息 Stringstr=in.readLine(); input=newBufferedReader(newInputStreamReader(System.in)); System.out.println("服务器显示-->客户端输入数据:"+str); out=newPrintWriter(socket.getOutputStream(),true); //将数据输出到客户端 //out.println("hehe"); Stringinfo=input.readLine(); out.println(info); } //in.close(); //out.flush(); //out.close(); } }
UDP
客户端:
importjava.net.DatagramPacket; importjava.net.DatagramSocket; publicclassUDPClient{ publicstaticvoidmain(String[]args)throwsException{ DatagramSocketds=null; DatagramPacketdp=null; byte[]buf=newbyte[1024]; ds=newDatagramSocket(3333); dp=newDatagramPacket(buf,1024); //接收数据,放入数据报 ds.receive(dp); //从数据报中取出数据 Stringinfo=newString(dp.getData(),0,dp.getLength()); System.out.println("接收到的信息是:"+info); } }
服务端:
importjava.net.DatagramPacket; importjava.net.DatagramSocket; importjava.net.InetAddress; publicclassUDPServer{ publicstaticvoidmain(String[]args)throwsException{ DatagramSocketds=null; DatagramPacketdp=null; //构建发送对象 ds=newDatagramSocket(); //将数据打包-->打成数据报 Stringinfo="helloworld!"; dp=newDatagramPacket(info.getBytes(),info.length(),InetAddress.getByName("localhost"),3333); //发出数据报 ds.send(dp); } }
以上这篇浅谈java的TCP和UDP编程(附实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。