JAVA套接字编程---UDP

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;


public class UDPClient {

    /**
     * @param args
     * @throws IOException 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        // TODO Auto-generated method stub
        DatagramSocket socket=new DatagramSocket(6790);
        Scanner input=new Scanner(System.in);
        System.out.println("input the string: ");
        String str=input.nextLine();
        byte[] str1=str.getBytes();
        DatagramPacket packet=new DatagramPacket(str1,str1.length,InetAddress.getLocalHost(),6789);
        socket.send(packet);
        System.out.println("将字符串送至服务器。。。");
        Thread.sleep(100);
        byte[] buf=new byte[1024];
        DatagramPacket packet2=new DatagramPacket(buf,buf.length);
        socket.receive(packet2);
        byte[] buf2=packet2.getData();
        String outstr=new String(buf2,0,packet2.getLength());
        System.out.println("从服务器返回结果:"+outstr);
        socket.close();

    }

}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class UDPServer {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        DatagramSocket server=new DatagramSocket(6789);
        byte[] recbuf=new byte[100];
        DatagramPacket recvpacket=
            new DatagramPacket(recbuf,recbuf.length);
        server.receive(recvpacket);
        System.out.println("服务器收到数据");
        String str1=new String(recvpacket.getData(),0,recvpacket.getLength());
        byte[] sendbuf=str1.toUpperCase().getBytes();
        DatagramPacket send=new DatagramPacket(sendbuf,sendbuf.length,InetAddress.getLocalHost(),6790);
        server.send(send);
        server.close();

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值