欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java Socket通信,客户端与服务端相互发消息

程序员文章站 2022-05-21 13:44:06
...

1.通信过程

网络分为应用层,http、ssh、telnet就是属于这一类,建立在传输层的基础上、其实就是定义了各自的编码解码格式,分层如下:
java Socket通信,客户端与服务端相互发消息

2.Socket连接

上述通信都要先在传输层有建立连接的基础上才能完成,TCP通过三次握手建立连接:
java Socket通信,客户端与服务端相互发消息
Socket与http的区别可以看下这个:
https://www.cnblogs.com/meier1205/p/5971313.html
还有搜索:http下午茶

3.JAVA socket 客户端与服务端互发消息

实现结构图:
java Socket通信,客户端与服务端相互发消息
客户端和服务端分别通过俩个线程来完成发送消息和接受消息,此前需要等待客户端与服务器端建立连接,这个java程序都帮你写好了,接收后就可以发消息了:

3.1 服务端代码


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


public  class  Server_Test extends Thread{
    ServerSocket server = null;
    Socket socket = null;
    public Server_Test(int port) {
        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run(){

        super.run();
        try{
            System.out.println("wait client connect...");
            socket = server.accept();
            new sendMessThread().start();//连接并返回socket后,再启用发送消息线程
            System.out.println(socket.getInetAddress().getHostAddress()+"SUCCESS TO CONNECT...");
            InputStream in = socket.getInputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len=in.read(buf))!=-1){
                System.out.println("client saying: "+new String(buf,0,len));
            }

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


    class sendMessThread extends Thread{
        @Override
        public void run(){
            super.run();
            Scanner scanner=null;
            OutputStream out = null;
            try{
                if(socket != null){
                    scanner = new Scanner(System.in);
                    out = socket.getOutputStream();
                    String in = "";
                    do {
                        in = scanner.next();
                        out.write(("server saying: "+in).getBytes());
                        out.flush();//清空缓存区的内容
                    }while (!in.equals("q"));
                    scanner.close();
                    try{
                        out.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //函数入口
    public static void main(String[] args) {
        Server_Test server = new Server_Test(1234);
        server.start();
    }
}

3.2 客户端代码


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

public class Client extends Thread {

    //定义一个Socket对象
    Socket socket = null;

    public Client(String host, int port) {
        try {
            //需要服务器的IP地址和端口号,才能获得正确的Socket对象
            socket = new Socket(host, port);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        //客户端一连接就可以写数据个服务器了
        new sendMessThread().start();
        super.run();
        try {
            // 读Sock里面的数据
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }

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

    //往Socket里面写数据,需要新开一个线程
    class sendMessThread extends Thread{
        @Override
        public void run() {
            super.run();
            //写操作
            Scanner scanner=null;
            OutputStream os= null;
            try {
                scanner=new Scanner(System.in);
                os= socket.getOutputStream();
                String in="";
                do {
                    in=scanner.next();
                    os.write((""+in).getBytes());
                    os.flush();
                } while (!in.equals("bye"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            scanner.close();
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //函数入口
    public static void main(String[] args) {
        //需要服务器的正确的IP地址和端口号
        Client clientTest=new Client("127.0.0.1", 1234);
        clientTest.start();
    }
}

输出:
服务器端:

wait client connect...
127.0.0.1SUCCESS TO CONNECT...
client saying: hi
i am server #服务端说得话
hi,client #服务端说得话
client saying: hi,server

客户端:

hi #客户端说得话
server saying: i
server saying: amserver saying: server
server saying: hi,client
hi,server #客户端说得话

参考:http://blog.csdn.net/wenzhi20102321/article/details/52620323
Java基础之网络编程知识点总结
http://blog.csdn.net/u011460827/article/details/41654257