UDP 无连接上机案例3.4
生活随笔
收集整理的這篇文章主要介紹了
UDP 无连接上机案例3.4
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;public class UDPServer {public static void main(String[] args) {//1.創(chuàng)建服務(wù)器端的DatagramSocket數(shù)據(jù)包,try {DatagramSocket datagramSocket=new DatagramSocket(8800);//2.創(chuàng)建數(shù)據(jù)報(bào),用于接受用戶傳送過(guò)來(lái)的數(shù)據(jù);存放于字節(jié)數(shù)組;byte[]bytes=new byte[1024];DatagramPacket datagramPacket=new DatagramPacket(bytes,bytes.length);System.out.println("*****服務(wù)器端已經(jīng)啟動(dòng)****");//使用receive方法接受;datagramSocket.receive(datagramPacket);//4.讀取數(shù)據(jù);String info=new String(bytes,0,datagramPacket.getLength());//5.輸出信息;System.out.println("服務(wù)器,客戶端信息為:"+info);//升級(jí)之后,服務(wù)器端響應(yīng)客戶端;InetAddress address=datagramPacket.getAddress();int port=datagramPacket.getPort();byte[]sinfo="歡迎您".getBytes();//升級(jí)2.創(chuàng)建數(shù)據(jù)報(bào),包含socket信息;DatagramPacket packet=new DatagramPacket(sinfo,sinfo.length,address,port);// 升級(jí)3;datagramSocket.send(packet);//關(guān)閉資源;datagramSocket.close();} catch (SocketException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}
客戶端代碼:
import java.io.IOException; import java.net.*;public class UDPClient {public static void main(String[] args) {//1.定義服務(wù)器的地址、端口號(hào)、數(shù)據(jù);try {InetAddress address=InetAddress.getByName("localhost");int port=8800;byte[]data="用戶名:admin,密碼:123".getBytes();//2.創(chuàng)建數(shù)據(jù)報(bào),包含發(fā)送的數(shù)據(jù)信息,可以使用帶有4個(gè)參數(shù)的方法;DatagramPacket datagramPacket=new DatagramPacket(data,data.length,address,port);//3.創(chuàng)建DatagramSocket對(duì)象;DatagramSocket datagramSocket=new DatagramSocket();//4.向服務(wù)器發(fā)送數(shù)據(jù);datagramSocket.send(datagramPacket);升級(jí)之后代碼段;byte[]data2=new byte[1024];DatagramPacket packet2=new DatagramPacket(data2,data2.length);//2.接受服務(wù)器響應(yīng)的數(shù)據(jù) ;datagramSocket.receive(packet2);//3.讀取數(shù)據(jù);String reply=new String(data2,0,packet2.getLength());System.out.println("我是客戶端,服務(wù)器端說(shuō):"+reply);//4.關(guān)閉資源;datagramSocket.close();} catch (UnknownHostException e) {e.printStackTrace();} catch (SocketException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} }服務(wù)端為:
總結(jié)
以上是生活随笔為你收集整理的UDP 无连接上机案例3.4的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java 网络通信必备之socket通信
- 下一篇: TCP面向连接的socket通信