网络(Socket)编程

网络编程:就是在网络上按照通信协议(TCP/UDP)传输数据,也就是说网络编程是建立在IO流与通信协议之上的,之前我已经学了IO流
我这里只记根据通信协议下的网络编程,即TCP和UDP,还有一个URL的通信,至于通信需要IP地址+端口号这类网络基础知识,我就不啰嗦了,遇到具体问题具体分析,先掌握大致的方法(通过自己写的例子来理解TCP/UDP的意义)
TCP举例:

package com.ligang.www;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import org.junit.Test;

public class TcpTest {
    /*1.创建一个socket,指明服务器的IP地址和端口号
     * 2.发送数据,并返回一个输出流
     * 3.发送什么
     * 4.发送
     * 5.告诉服务器我已经发送完毕
     * 6.接收来自服务端的数据并将它们输出到终端
     * 7.从下往上关闭文件流
     */
    @Test
    public void cliver(){
        Socket ss = null;
        OutputStream ee = null;
        Scanner dd = null;
        InputStream bb = null;
        try {
            ss = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            ee = ss.getOutputStream();
            System.out.println("请输入字符串:");
            dd = new Scanner(System.in);
            String str=dd.next();
            ee.write(str.getBytes());
            ss.shutdownOutput();
            bb = ss.getInputStream();
            byte [] b=new byte[10];
            int len;
            while((len=bb.read(b))!=-1){
                String str2=new String(b, 0, len);
                System.out.println(str2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            if(bb!=null){
                try {
                    bb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dd!=null){
                dd.close();
            }
            if(ee!=null){
                try {
                    ee.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void sever(){
        /*1.创建一个ServerSocket的对象,通过构造器指明自身的端口
            2.调用其accept()方法,返回一个Socket的对象
            3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
            4.对获取的输入流进行的操作,将其转换成大写
            5.调用Socket对象的getOutputStream()获取一个向服务器法搜数据的输出流
            6.将转换后的字符串发送给客户端
            7.依次关闭文件流
         */
        ServerSocket ss = null;
        Socket e = null;
        InputStream ee = null;
        OutputStream r = null;
        try {
            ss = new ServerSocket(9090);
            e = ss.accept();
            ee = e.getInputStream();
            byte [] b=new byte[10];
            int len ;
            String str=new String();
            while((len=ee.read(b))!=-1){
                String str1=new String(b, 0, len);
                str=str1+str;
            }
            String str3=str.toUpperCase();
            r = e.getOutputStream();
            r.write(str3.getBytes());
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {
            if(r!=null){
                try {
                    r.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(ee!=null){
                try {
                    ee.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(e!=null){
                try {
                    e.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(ss!=null){
                try {
                    ss.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


}

UDP举例:

package com.ligang.www;

import java.io.*;
import java.net.*;

import org.junit.Test;

/*
 * UDP数据报通过数据报套接字 DatagramSocket 发送和接收
 * DatagramPacket 对象封装了UDP数据报,
 * 在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号
 */
public class UdpTest {
    @Test
    public void send(){//發送端
        DatagramSocket ds=null;
        try {
            ds = new DatagramSocket();//定义一个udp的socket接口负责发送数据
            byte b[]="你好 ,我来看你来了".getBytes();//定义一个发送数据的数组
            DatagramPacket fs=new DatagramPacket(b,0,b.length,
                    InetAddress.getByName("127.0.0.1"), 9875);//定义一个udp的socket包,负责数据传输
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(ds!=null){
                ds.close();//關閉socket接口
            }
        }
    }
    @Test
    public void revice(){//接收端
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(9875);//在接收端接收來自發送端的接口
            byte [] b=new byte [1024];//定義一個數組專門做接收的容器
            DatagramPacket fs = new DatagramPacket(b, 0, b.length);
            ds.receive(fs);//定義一個udp的包來接收發送端的數據包
            String str =new String(fs.getData(), 0, fs.getLength());//將接受到的數據包轉化成字符串的形式以便輸出
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(ds!=null){
                ds.close();//關閉
            }
        }
    }

}

URL举例:

package com.ligang.www;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Test;

public class UrlTest {
    @Test
    public void Url(){
        InputStream is =  null;
        InputStream is2=  null;
        FileOutputStream fos=null;
        try {
            URL url =new URL("http://127.0.0.1:8080/examples/javac---.txt");//先建立一条指定的链接
            URLConnection url1 = url.openConnection();//这个类既可以从网络上读数据,也可以发数据
            is = url.openStream();//这个类仅仅能从网络上读取数据,不能将数据发送回去
            is2=url1.getInputStream();//从网络上读取数据
            fos=new FileOutputStream(new File("178.txt"));//建立一个文件来存储将要从服务器下载下来数据
            byte [] b=new byte[10];
            int len;
            while((len=is.read(b))!=-1){//将从服务器获取到的数据输出到终端上
                String str=new String(b, 0, len);
                System.out.print(str);
            }
            while ((len=is2.read(b))!=-1){//将从服务器获取到的数据输出到文件中
                fos.write(b, 0, len);
            }
        } 
         catch (IOException e) {
            e.printStackTrace();
        }finally{//从前往后依次关闭文件流
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

        }
    }

注释:上面的例子 中抛了好多的异常,那是系统自己抛的 我们只要捕获就行,IO和Socket接口资源是非常珍贵的系统资源,一定要记得关闭

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值