初始网络编程

文章展示了Java中使用InetAddress和Socket进行TCP与UDP通信的基本步骤,包括客户端连接服务器、发送消息以及服务器端接收和响应。此外,还提供了TCP协议下实现文件上传的客户端和服务器端代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

 

 

 

 

 

package com.kuang.lessonip;

import java.net.InetAddress;
import java.net.UnknownHostException;

//测试IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
//            查询本地地址  3种方式
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);
//            查询网站地址
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
}

端口 

 

 

 

 

 

 TCP:嘴巴对着瓶子喝水;UDP:瓶子抬起来喝水

 两个socket是因为serverSocket中没有没有inputsteam而socket中有   通过accept()方法可以获取socket对象再获取inputsteam读我们要接收的数据

JDK1.7之后不需要在finally中手动关闭,只需要在try()小括号中写入流对象实例就会自动托管帮你关闭

if(流 != null)不是指数据还在传输,意思是通过这个判断流有传输数据,finally时数据已经传输完毕, 此时数据流已经不再传输了,但功能还在,通过这个判断能够有效准确地关闭传输流。

TCP/IP

客户端

1.连接服务器Socket

2.发送消息

package com.kuang.lesson02;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket=null;
        OutputStream oS=null;
        try {
            //1.要知道服务器的地址
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
//            2.端口号
            int port=9999;
          //3.创建一个socket连接
            socket = new Socket(serverIP,port);

            //4.发送消息
           oS = socket.getOutputStream();
        oS.write("你好,欢迎学习Java".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (oS!=null){
                try {
                   oS.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }


}

服务器

1.建立服务的端口  ServerSocket

2.等待用户的连接 通过accept();

3.接收用的消息

package com.kuang.lesson02;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class TcpServerDemo01 {
    public static void main(String[] args) {
        //1.我得有一个地址
        Socket socket=null;
        InputStream iS=null;
        ByteArrayOutputStream baos=null;
        ServerSocket serverSocket=null;
        try {
            serverSocket = new ServerSocket(9999);
            while(true){

                //2.等待客户端链接过来
                socket = serverSocket.accept();
                //3.获取客户端的信息
                iS = socket.getInputStream();

                //管道流
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = iS.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            关闭资源
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(iS!=null){
                try {
                    iS.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

TCP/IP文件上传

客户端

package com.kuang.lesson02;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
//        1.创建一个Socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//        2.创建一个输出流
        OutputStream os = socket.getOutputStream();
//        3.读取文件
        FileInputStream fis = new FileInputStream(new File("a.jpg"));
//        4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while (((len = fis.read(buffer))) != -1) {
            os.write(buffer, 0, len);
        }
        //通知服务器,我已经结束了
        socket.shutdownOutput();//我已经传输完了!

        //确定服务器接收完毕,才能断开连接
        InputStream inputStream = socket.getInputStream();
      //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

      byte[]  buffer2 =  new byte[1024];
      int len2;
      while ((len2=inputStream.read(buffer2))!=-1){
          baos.write(buffer2,0,len2);
      }
        System.out.println(baos.toString());
//        5.关闭数据
       baos.close();
       inputStream.close();

        fis.close();
        os.close();
        socket.close();

    }

}

服务器端

package com.kuang.lesson02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpServerDemo02 {
    public static void main(String[] args) throws IOException {
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.监听客户端的链接
        Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接;
        //3.获取输入流
        InputStream iS = socket.getInputStream();
        //4.文件输出
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=iS.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }

        //通知客户端我接收完毕了
        OutputStream oS = socket.getOutputStream();
        oS.write("我接收完毕了,你可以断开了".getBytes());


        //关闭资源
        fos.close();
        iS.close();
        socket.close();
        serverSocket.close();


    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值