首页 > 编程语言 > 详细

java学习---网络编程

时间:2020-09-05 17:45:02      阅读:79      评论:0      收藏:0      [点我收藏+]

网络编程

网络通信要素

通信双方地址

  • ip
  • 端口号

通信协议
TCP/IP

IP地址

InetAddress类

  • 唯一定位一台网络上计算机
  • 127.0.0.1:本机localhost
  • ip地址分类
    ipv4、ipv6
    公网-私网
  • 域名

端口

端口表示计算机上的一个程序的进程

  • 不同的进程有不同的端口号,用来区分软件
  • TCP,UDP

socketAddress类

通信协议

TCP/IP协议:实际上是一组协议

  • TCP:用户传输协议
  • UDP:用户数据报协议

对比
tcp:打电话

  • 连接,稳定
  • 三次握手、四次挥手
  • 客户端、服务端
  • 传输完成,释放连接,效率低

udp:发短信

  • 不连接,不稳定
  • 客户端、服务端:没有明确的界限
  • 不管有没有准备好,都可以发

TCP

客户端

  1. 连接服务器socket
  2. 发送消息

服务器

  1. 建立服务的端口ServerSocket
  2. 等待用户的消息
  3. 接收用的消息

文件上传

package test.net.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket
;
public class FileUploadServer {??? 
public static void main(String[] args) throws 
IOException {???????
ServerSocket serverSocket = new ServerSocket(9999);???
Socket socket = serverSocket.accept();?????
InputStream is = socket.getInputStream();????
byte[] buffer = new byte[1024];???
int len ;??
FileOutputStream fos = new FileOutputStream(new File(("2.jpg")));??
while ((len=is.read(buffer))!=-1){???????
fos.write(buffer,0,len);??????? }????
fos.close();?????
is.close();??????
socket.close();????
serverSocket.close();??? }}


package test.net.file;
import java.io.*;
import java.net.Socket;
public class FileUploadClient {??
public static void main(String[] args) throws IOException {?????
Socket socket = new Socket("localhost",9999);?????
OutputStream os = socket.getOutputStream();??
FileInputStream fis = new FileInputStream(new File("1.jpg"));?????
byte[]? buffer= new byte[1024];?????
int len;??????
while ((len=fis.read(buffer))!=-1){??????
os.write(buffer,0,len);??????? }

socket.shutdownOutput();

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




UDP

package test.net.udp;import java.net.*;public class UdpClient1 {??? public static void main(String[] args) throws Exception {????
DatagramSocket socket = new DatagramSocket();?????
String msg = "hello";??????
InetAddress localhost =InetAddress.getByName("localhost");??????? int port = 9090;??????
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.length(), 
localhost, port);??????? socket.send(packet);????
socket.close();??? }}



package test.net.udp;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class UdpServer1 {?
public static void main(String[] args) throws 
Exception {??????
DatagramSocket socket = new 
DatagramSocket();????
byte[] buffer = new byte[1024];?????
int len;?????
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);??????? socket.receive(packet);??????? 
System.out.println(packet.getAddress().getHostAddress());?
System.out.println(new String(packet.getData(),0,packet.getLength()));????
socket.close();??? }}





循环发送

package test.net.chat;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpSend {
    public static void main(String[] args) throws Exception {
        //1.创建socket
        DatagramSocket socket = new DatagramSocket(8888);
        //2.创建packet
        //2.1从键盘获取内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            //2.2装包
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
            //3.发送
            socket.send(packet);
            if ("bye".equals(data)){
                break;
            }
        }


        socket.close();
    }
}


--------------------------
    package test.net.chat;


import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpRece {
    public static void main(String[] args) throws Exception {
        //1.创建socket
        DatagramSocket socket = new DatagramSocket(6666);
        while (true) {
            //2.创建packet
            //2.1 装数据容器
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            //3.接收
            socket.receive(packet);
            //4.打印内容
            byte[] data = packet.getData();
            
            //注意要packet.getLength()
            String receData = new String(data, 0, packet.getLength());
            System.out.println(receData);
            //4.1结束判断
            if ("bye".equals(receData)){
                break;
            }
        }
        //5.关闭
        socket.close();
    }
}

聊天室

package test.net.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend implements Runnable{

    DatagramSocket socket;
    BufferedReader reader;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //2.1从键盘获取内容
        while (true){
            String data = null;
            try {
                data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                socket.send(packet);
                if ("bye".equals(data)){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


        socket.close();
    }
}
-----------------------------
package test.net.chat;

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

public class TalkRece implements Runnable{
    DatagramSocket socket =null;

    private int port;
    private String msgFrom;

    public TalkRece(int port,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;

        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            try {
                socket.receive(packet);
                byte[] data = packet.getData();
                String receData = new String(data, 0, packet.getLength());
                System.out.println(msgFrom+":"+receData);
                if ("bye".equals(receData)){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        socket.close();
    }
}

url

url.getProtocol()
url.getHost()
url.getPort()
url.getPath()
url.getFile()
url.getQuery()

//下载资源
HttpURLConnection urlConn = (HttpUrlConnection)url.openConnection();
urlConn.getInputStream()

java学习---网络编程

原文:https://www.cnblogs.com/bbb0717/p/13618741.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!