Java教程

JAVA学习-网络编程

本文主要是介绍JAVA学习-网络编程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

TCP实现聊天(Local)

服务端

package com.myTCP.chatDemo;

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

public class ServerChat {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            //服务端需要一个地址
            serverSocket = new ServerSocket(829);
            //服务端等待客户端的连接 accept方法,就是等待客户端连接
            socket = serverSocket.accept();
            //读取客户端消息 
            inputStream = socket.getInputStream();
            //管道流用于输出
            baos =new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int Len;
            while ((Len = inputStream.read(bytes)) != -1){
                baos.write(bytes,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 (inputStream != null){
                try {
                    inputStream.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();
                }
            }
        }
    }
}

客户端

package com.myTCP.chatDemo;

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

public class ClientChat {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //获得服务端IP
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            //填写服务端IP和端口到客户端
            socket = new Socket(serverIP,829);
            //输出流连到客户端的输出方法
            os = socket.getOutputStream();
            //输出流输出内容
            os.write("hello,world!".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();
                }
            }
        }

    }
}

TCP文件上传(Local)

UDP发短信(Local)

初级

发送端

package com.myUDP.chatDemo01;

import java.net.*;

public class mySend {
    public static void main(String[] args) {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            String msg ="hello,world";
            InetAddress localhost = InetAddress.getByName("localhost");
            int port = 829;
            DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.length(),localhost,port);
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
}

接收端

package com.myUDP.chatDemo01;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;

public class myReceive {
    public static void main(String[] args) {
        DatagramSocket socket = null;
        DatagramPacket packet = null;
        try {
            socket = new DatagramSocket(829);//设置自己接收的端口
            byte[] buffer = new byte[1024];//缓冲区
            packet = new DatagramPacket(buffer,0,buffer.length);//接收数据包
            socket.receive(packet);//阻塞式监听
            System.out.println(new String(packet.getData(),0,packet.getLength()));//输出数据包接收到的内容

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

实现控制台循环发送

发送端:

package com.myUDP.demo02;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

public class Demo02 {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(666) ;

            while (true){

                byte[] bytes = new byte[1024];
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String sendBytes = reader.readLine();
                bytes = sendBytes.getBytes();

                InetAddress inetAddress = InetAddress.getLocalHost();

                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,inetAddress,888 );

                socket.send(packet);

                if (sendBytes.equals("bye")){
                    break;
                }
            }

            socket.close();
            

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

接收端

package com.myUDP.demo02;

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


public class Demo02b {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(888);
            while (true){

                byte[] buff = new byte[1024];

                DatagramPacket packet = new DatagramPacket(buff,0,buff.length);

                socket.receive(packet);


                System.out.println(new String(buff,0, packet.getLength()));//注意,这里必须是获取packet的长度,byte[]的长度是1024!!

                if (new String(buff,0, packet.getLength()).equals("bye")){
                    break;
                }
            }
            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

实现多线程交互式聊天

发送消息线程

package com.myUDP.demo04;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class SendMsg implements Runnable{
    DatagramSocket socket;
    BufferedReader reader;
    private int toIP;
    private int fromIP;

    public SendMsg(int toIP, int fromIP) {
        this.toIP = toIP;
        this.fromIP = fromIP;
    }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket(fromIP) ;
            reader = new BufferedReader(new InputStreamReader(System.in));
            while (true){

                byte[] bytes = new byte[1024];

                String sendBytes = reader.readLine();
                bytes = sendBytes.getBytes();

                InetAddress inetAddress = InetAddress.getLocalHost();

                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,inetAddress,toIP );

                socket.send(packet);

                if (sendBytes.equals("bye")){
                    break;
                }
            }

            socket.close();
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

接收消息线程

package com.myUDP.demo04;

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

public class ReceiveMsg implements Runnable{
    DatagramSocket socket;
    private int recIP;
    private String recName;

    public ReceiveMsg(int recIP, String recName) {
        this.recIP = recIP;
        this.recName = recName;
    }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket(recIP);
            while (true){

                byte[] buff = new byte[1024];

                DatagramPacket packet = new DatagramPacket(buff,0,buff.length);

                socket.receive(packet);


                System.out.println(recName+":"+new String(buff,0, packet.getLength()));//注意,这里必须是获取packet的长度,byte[]的长度是1024!!

                if (new String(buff,0, packet.getLength()).equals("bye")){
                    break;
                }
            }
            socket.close();
            System.exit(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

客户端启动线程

package com.myUDP.demo04;

public class Student {
    public static void main(String[] args) {
        new Thread(new SendMsg(888,01)).start();
        new Thread(new ReceiveMsg(666,"老师")).start();
    }
}
////////////////////////////////
package com.myUDP.demo04;

public class Teacher {
    public static void main(String[] args) {
        new Thread(new SendMsg(666,02)).start();
        new Thread(new ReceiveMsg(888,"学生")).start();
    }
}

关于try-catch遇到的问题

注意一个问题!!! try-catch 里面new的对象一旦离开了try-catch就没了,会出现空指针异常。

但如果是放在构造器里面,相当于一出生就new了,是可以使用的!!!

例如,举个例子,发送线程:

package com.myUDP.demo03;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class SendMsg implements Runnable {
    DatagramSocket socket = null;
    DatagramPacket packet = null;
    private int toPort;
    private int formPort;
    BufferedReader reader = null;

    public SendMsg( int toPort, int formPort) {
        this.toPort = toPort;
        this.formPort = formPort;
        try {
            this.socket = new DatagramSocket(formPort);
            this.reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {


            try {
                while (true){
                    //String sendBytes = this.reader.readLine();
                    byte[] bytes = this.reader.readLine().getBytes(); //这里不要定义1024,因为不清楚具体长度

                    this.packet = new DatagramPacket(bytes,0,bytes.length,InetAddress.getLocalHost(),toPort);
                    this.socket.send(packet);
                    String sendBytes = new String(bytes,0, bytes.length);
                    if (sendBytes.equals("bye")){
                        break;
                }


                    socket.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


    }
}

这篇关于JAVA学习-网络编程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!