浅谈java的TCP和UDP编程(附实例讲解)
程序员文章站
2023-12-20 19:20:16
tcp
客户端:
import java.io.bufferedreader;
import java.io.inputstreamreade...
tcp
客户端:
import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.printwriter; import java.net.socket; public class myclient { public static void main(string[] args) throws exception{ socket socket = null; bufferedreader in = null; printwriter out = null; bufferedreader input = null; // 请求指定ip和端口号的服务器 socket = new socket("127.0.0.1",3333); while(true){ in = new bufferedreader(new inputstreamreader(socket.getinputstream())); out = new printwriter(socket.getoutputstream(), true); // 接收控制台的输入 input = new bufferedreader(new inputstreamreader(system.in)); // out.println("this is client info!"); string info = input.readline(); out.println(info); string str = in.readline(); system.out.println("客户端显示--》服务器的信息:" + str); } //in.close(); //out.close(); } }
服务端:
import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.printwriter; import java.net.serversocket; import java.net.socket; public class myservices { public static void main(string[] args) throws exception{ serversocket ss = null; socket socket = null; bufferedreader in = null; printwriter out = null; bufferedreader input = null; // 监听3333端口 ss = new serversocket(3333); // 等待接收客户端的请求 socket = ss.accept(); while(true){ // 获取连接对象的输入流 in = new bufferedreader(new inputstreamreader(socket.getinputstream())); // 获取客户端的输入信息 string str = in.readline(); input = new bufferedreader(new inputstreamreader(system.in)); system.out.println("服务器显示-->客户端输入数据:" + str); out = new printwriter(socket.getoutputstream(),true); // 将数据输出到客户端 // out.println("hehe"); string info = input.readline(); out.println(info); } // in.close(); // out.flush(); // out.close(); } }
udp
客户端:
import java.net.datagrampacket; import java.net.datagramsocket; public class udpclient { public static void main(string[] args) throws exception { datagramsocket ds = null; datagrampacket dp = null; byte[] buf = new byte[1024]; ds = new datagramsocket(3333); dp = new datagrampacket(buf, 1024); // 接收数据,放入数据报 ds.receive(dp); // 从数据报中取出数据 string info = new string(dp.getdata(),0, dp.getlength()); system.out.println("接收到的信息是:" + info); } }
服务端:
import java.net.datagrampacket; import java.net.datagramsocket; import java.net.inetaddress; public class udpserver { public static void main(string[] args) throws exception { datagramsocket ds = null; datagrampacket dp = null; // 构建发送对象 ds = new datagramsocket(); // 将数据打包-->打成数据报 string info = "hello world!"; dp = new datagrampacket(info.getbytes(), info.length(), inetaddress.getbyname("localhost"),3333); // 发出数据报 ds.send(dp); } }
以上这篇浅谈java的tcp和udp编程(附实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。