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

标签: 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();
    }
}

实验结果:

 

版权声明:本文为weixin_43731933原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43731933/article/details/108831212