udp客户端 Java_【Java学习笔记】UDP客户端/服务器端

客户端:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

import java.net.UnknownHostException;

import java.io.IOException;

public class UdpClient {

public static void main(String arg[]) {

String outstr;

if(arg.length >= 1)

outstr = arg[0];

else

outstr = "count";

try {

DatagramSocket socket = new DatagramSocket();

byte outblock[] = outstr.getBytes();

InetAddress address = InetAddress.getLocalHost();

DatagramPacket outpacket =

new DatagramPacket(outblock,outblock.length,address,8765);

socket.send(outpacket);

System.out.println("Client sent: " + outstr);

byte inblock[] = new byte[256];

DatagramPacket inpacket =

new DatagramPacket(inblock,inblock.length);

socket.receive(inpacket);

String instr = new String(inpacket.getData(),0,inpacket.getLength());

System.out.println("Client got: " + instr);

socket.close();

} catch(SocketException e) {

System.out.println(e);

} catch(UnknownHostException e) {

System.out.println(e);

} catch(IOException e) {

System.out.println(e);

}

}

}

服务器端:

import java.net.DatagramSocket;

import java.net.DatagramPacket;

import java.net.InetAddress;

import java.io.IOException;

import java.util.Date;

public class UdpServer {

public static void main(String arg[]) {

DatagramSocket socket = null;

int count = 0;

try {

socket = new DatagramSocket(8765);

} catch(IOException e) {

System.out.println(e);

}

while(true) {

try {

byte block[] = new byte[256];

DatagramPacket inpacket

= new DatagramPacket(block,block.length);

socket.receive(inpacket);

int length = inpacket.getLength();

System.out.println("Length of the data received: " + length);

byte inblock[] = inpacket.getData();

String inmsg = new String(inblock,0,length);

System.out.println("Server got: " + inmsg);

count++;

String outmsg;

if(inmsg.equals("date")) {

Date date = new Date();

outmsg = date.toString();

} else if(inmsg.equals("halt")) {

socket.close();

return;

} else if(inmsg.equals("count")) {

outmsg = "Number of messages: " + count;

} else {

outmsg = "What is " + inmsg + "?";

}

byte outblock[] = outmsg.getBytes();

InetAddress returnaddress = inpacket.getAddress();

int returnport = inpacket.getPort();

DatagramPacket outpacket = new DatagramPacket(

outblock,outblock.length,returnaddress,returnport);

socket.send(outpacket);

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值