即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

Java语言网络编程

编程语言 sinat_32323511 24℃ 0评论
本文目录
[隐藏]

1.1.通过InetAddress获取IP地址

public class IPDemo {
    public static void main(String[] args) throws Exception
    {
        //获取本机的IP地址
        InetAddress i=InetAddress.getLocalHost();
        System.out.println(i.toString());
        System.out.println("address:"+i.getHostAddress());//主要方式,速度快
        System.out.println("name:"+i.getHostName());
        //域名下映射多个ip获取方式
        InetAddress[] ias=InetAddress.getAllByName("www.baidu.com");
        for(InetAddress i:ias){
            System.out.println(i.toString());
        }
        InetAddress ia=InetAddress.getByName("www.baidu.com");
        System.out.println(ia.toString());//默认获得第一个IP地址 
    }
}

2.2.udp方式发送和接收数据

  • 发送端
public class UdpSend2 {
    public static void main(String[] args) throws Exception 
    {
        DatagramSocket ds=new DatagramSocket(6666);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String line=null;
        while((line=br.readLine())!=null){
            if(line.equals("886")){
                break;
            }
            byte[] buf=line.getBytes();
            DatagramPacket dp=new DatagramPacket(buf,     buf.length,InetAddress.getByName("192.168.XXX.XX"),10001);
            ds.send(dp);
        }
        ds.close();
    }
}
  • 接收端
public class UpdReceive2 {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds =new DatagramSocket(10001);
        while(true){
            byte[] buf=new byte[1024];
            DatagramPacket dp=new DatagramPacket(buf, buf.length);
            ds.receive(dp);//阻塞式方法
            String ip=dp.getAddress().getHostAddress();
            String data=new String(dp.getData(),0,dp.getLength());
            System.out.println(ip+":"+data);
        }
//      ds.close();
    }
}

注意:运行时先开启接收端,再开启发送端

  • 多线程聊天小程序
class Send implements Runnable{

    private DatagramSocket ds;
    public Send(DatagramSocket ds){
        this.ds=ds;
    }

    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String line=null;
            while((line=br.readLine())!=null){
                byte[] buf=line.getBytes();
                DatagramPacket dp=new DatagramPacket(buf, buf.length,InetAddress.getByName("192.168.XXX.XXX"),10002);
                ds.send(dp);
            }   
        } catch (Exception e) {
            throw new RuntimeException("发送端失败!");
        }
    }

}

class Receive implements Runnable{
    private DatagramSocket ds;
    public Receive(DatagramSocket ds){
        this.ds=ds;
    }
    public void run() {
        try {
            while(true){
                byte[] buf=new byte[1024];
                DatagramPacket dp=new DatagramPacket(buf, buf.length);
                ds.receive(dp);
                String ip=dp.getAddress().getHostAddress();
                String data=new String(dp.getData(),0,dp.getLength());
                System.out.println(ip+":"+data);

            }
        } catch (Exception e) {
            throw new RuntimeException("接收端失败!");
        }
    }

}

public class ChatDemo {
    public static void main(String[] args) throws Exception {
        DatagramSocket sendDs=new DatagramSocket();
        DatagramSocket receiveDs=new DatagramSocket(10002);
        new Thread(new Receive(receiveDs)).start();
        new Thread(new Send(sendDs)).start();
    }
}

3.3.tcp方式接收和发送数据

  • 客户端
public class TcpClient{
    public static void main(String[] args) throws Exception {
        //创建客户端的socket服务,指定目的主机和端口
        Socket s=new Socket("169.254.X.X",10003);
        //为了发送数据,应该获取socket流中的输出流
        OutputStream out=s.getOutputStream();
        out.write("TCP哥们来了".getBytes());
        s.close();
    }
}
  • 服务端
class TcpServer{
    public static void main(String[] args) throws Exception {
        //建立服务端socket服务。并监听一个端口
        ServerSocket ss=new ServerSocket(10003);
        //通过accept方法获取链接过来的客户端对象
        Socket s=ss.accept();
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+".....connected");
        //获取客户端发送过来的数据,使用输入流来读取
        InputStream in=s.getInputStream();
        byte[] buf=new byte[1024];
        int len=in.read(buf);
        System.out.println(new String(buf,0,len));
        s.close();
        ss.close();
    }
}
  • 大小写转换案例
//客户端
public class TransClient {
    public static void main(String[] args) throws Exception {
        Socket s=new Socket("169.254.X.X", 10004);
        //获取键盘输入
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

        //定义一个读取流,读取服务端返回的大写字母
        BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));

        //将数据写到输出流发送到服务端
//      BufferedWriter bufOut=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        //或者
        PrintWriter pw=new PrintWriter(s.getOutputStream(),true);

        String line=null;
        while((line=br.readLine())!=null){
            if("over".equals(line))
                break;
//          bufOut.write(line);
//          bufOut.newLine();
//          bufOut.flush();
            pw.println(line);
            String str=bufIn.readLine();
            System.out.println("server:"+str);
        }
        br.close();
        s.close();
    }
}

//服务端
public class TransServer {
    public static void main(String[] args) throws Exception{
        ServerSocket ss=new ServerSocket(10004);
        Socket s=ss.accept();
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+"......connected");
        //读取客户端键盘录入的字母
        BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));

//      BufferedWriter bufOut=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        PrintWriter pw =new PrintWriter(s.getOutputStream(), true);
        String line=null;
        while((line=bufIn.readLine())!=null){

//          bufOut.write(line.toUpperCase());
//          bufOut.newLine();
//          bufOut.flush();
            pw.println(line.toUpperCase());
        }
        s.close();
        ss.close();

    }
  • 上传文件案例
//客户端
public class TextClient {
    public static void main(String[] args) throws Exception {
        Socket s=new Socket("169.254.x.x",10005);
        BufferedReader bufr=new BufferedReader(new FileReader("F:\\工作区\\APIs\\sql注入.txt"));
        PrintWriter out=new PrintWriter(s.getOutputStream(),true);

        String line=null;
        while((line=bufr.readLine())!=null){
            out.println(line);
        }
        s.shutdownOutput();//关闭客户端的输出流,相当于给流中加入了结束标记-1

        BufferedReader bufIn=new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str=bufIn.readLine();
        System.out.println(str);//接收服务端传过来的上传成功字样

        bufr.close();
        s.close();

    }
}
//服务端
public class TextServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss=new ServerSocket(10005);
        Socket s=ss.accept();
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+"....connected");

        BufferedReader buIn=new BufferedReader(new InputStreamReader(s.getInputStream()));

        PrintWriter out=new PrintWriter(new FileWriter("D:\\1.txt"),true);

        String line = null;
        while((line=buIn.readLine())!=null){
            out.println(line);
        }


        PrintWriter pw =new PrintWriter(s.getOutputStream(),true);
        pw.println("上传成功!");

        out.close();
        s.close();
        ss.close();
    }
}
  • 上传图片案例
//客户端
public class PicClient {
    public static void main(String[] args) throws Exception {
        Socket  s=new Socket("192.168.x.x", 10006);

        FileInputStream fis=new FileInputStream("E:\\图片\\b9.jpg");

        OutputStream out=s.getOutputStream();
        byte[] buf=new byte[1024];
        int len=0;
        while((len=fis.read(buf))!=-1){
            out.write(buf,0,len);
        }
        //告诉服务器数据已写完
        s.shutdownOutput();

        byte[] str=new byte[1024];
        InputStream in=s.getInputStream();
        int num=in.read(str);
        System.out.println(new String(str,0,num));

        fis.close();
        s.close();
    }

}
//服务端
public class PicServer {
    public static void main(String[] args) throws Exception{
        ServerSocket ss=new ServerSocket(10006);
        Socket s=ss.accept();
        String ip=s.getInetAddress().getHostAddress();
        System.out.println(ip+"......connected");
        InputStream in=s.getInputStream();
        FileOutputStream fos=new FileOutputStream("d:\\1.jpg");
        int len=0;
        byte[] buf =new byte[1024];
        while((len=in.read(buf))!=-1){
            fos.write(buf,0,len);
        }
        OutputStream out=s.getOutputStream();
        out.write("上传成功".getBytes());
        fos.close();
        s.close();
        ss.close();
    }
}

转载请注明:CodingBlog » Java语言网络编程

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情