TCP:客户端向服务端发送用户名请求登陆。

问题:

客户端向服务端发送用户名请求登陆,服务端通过验证,返回“欢迎光临”,未通过“用户不存在”。

客户端:

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

public class client
{
    public static void send() throws IOException
    {
        Scanner in = new Scanner(System.in);
        Socket now = new Socket("127.0.0.1", 10000);
        OutputStream out = now.getOutputStream();
        out.write(in.nextLine().getBytes());
        now.close();
        out.close();
    }
    public static void receive() throws IOException
    {
        ServerSocket now = new ServerSocket(9989);
        Socket ac = now.accept();
        InputStream in = ac.getInputStream();
        int num = 0;
        byte[] u = new byte[1024];
        while ((num = in.read(u)) != -1)
        {
            System.out.print(new String(u, 0, num));
        }
        in.close();
        now.close();
    }
    public static void main(String[] args) throws IOException
    {
        send();
        receive();
    }
}

服务端:

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

public class server
{
    public static void send(String info) throws IOException
    {
        Socket now = new Socket("127.0.0.1", 9989);
        OutputStream out = now.getOutputStream();
        out.write(info.getBytes());
        now.close();
        out.close();
    }
    public static void receive() throws IOException
    {
        ServerSocket now = new ServerSocket(10000);
        Socket ac = now.accept();
        InputStream in = ac.getInputStream();
        int num = 0;
        byte[] u = new byte[1024];
        StringBuffer res = new StringBuffer();
        while ((num = in.read(u)) != -1)
        {
            String tmp = new String(u, 0, num);
            res.append(tmp);
        }
        String info = new String(res);
        if (info.compareTo("jin") == 0)
            send("欢迎光临");
        else
            send("用户不存在");
        in.close();
        now.close();
    }
    public static void main(String[] args) throws IOException
    {
       receive();
    }
}

实验结果:

猜你喜欢

转载自blog.csdn.net/weixin_43731933/article/details/108831212