会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132376个问题
JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 3406楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/数据结构 3407楼

先运行服务器端,服务器启动没报错,再启动客户端,也没报错,输入账号密码之后客户端报错如下截图,然后发现服务器端也报错,不知道是什么原因。


项目目录结构截图

image.png


错误截图:

客户端

image.png


服务器端

image.png



附上代码:


客户端

package com.cn.entity;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 基于TCP协议的Socket编程_双向通信_实现模拟用户登录
 */
public class Client {

    public static void main(String[] args) throws IOException {
        //(1)创建Socket对象,用于连接服务器
        Socket client=new Socket("localhost", 8888);
        //(2)获取输出流  (对象流)
        ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
        //(3)创建User对象
        //调用获取用户对象的方法
        User u=getUser();//new User("bjsxt", "bjsxt");
        //(4)User对象发送到服务器
        oos.writeObject(u);

        //(5)获取输入流(数据流)
        DataInputStream dis=new DataInputStream(client.getInputStream());
        System.out.println(dis.readUTF());
        //(6)关闭流
        if(dis!=null){
            dis.close();
        }
        if(oos!=null){
            oos.close();
        }
        if(client!=null){
            client.close();
        }
    }
    //获取用户对象的方法
    public static User getUser(){
        Scanner input=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userName=input.next();
        System.out.println("请输入密码:");
        String password=input.next();
        //封装成User对象
        return new User(userName,password);
    }
}

User类

package com.cn.entity;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = -5699785428357564782L;
    private String userName;
    private String passWord;

    public User(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    public User() {
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}




服务器端

package com.cn.entity;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于TCP协议的Socket编程_双向通信_实现模拟用户登录
 */
public class Server {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        System.out.println("--------------服务器端已启动---------------");
        //(1)创建SocketServer对象
        ServerSocket server = new ServerSocket(8888);  //10000是端口号
        Socket socket = server.accept();
        //(2)获取输入流(对象流) ,把字节流包装成对象流
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

        //读Object类型,向上类型转换
        User2 user = (User2) ois.readObject();
        System.out.println(socket.getInetAddress().getHostAddress()+"请求登录");
        System.out.println("用户名:"+user.getUserName());
        System.out.println("密码:"+user.getPassWord());


        //(3)堆用户名和密码进行验证
        String str = "";
        if ("bjsxt".equals(user.getUserName())&&"bjsxt".equals(user.getPassWord())){
            str="登录成功";
        }else {
            str="对不起,账号密码不正确!";
        }
        //(4)获取输出流(数据流),把字节流包装成数据流
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(str);
        //(5)关闭流,关闭SockerServer
        if (dos!=null){
            dos.close();
        }
        if (ois!=null){
            ois.close();
        }
        if (socket!=null){
            socket.close();
        }


    }

}

User2类

package com.cn.entity;

import java.io.Serializable;

public class User2 implements Serializable {

    private static final long serialVersionUID = -5699785428357564782L;
    private String userName;
    private String passWord;

    public User2(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    public User2() {
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}


JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 3412楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/数据结构 3413楼

为什么输出后没有名字

/**
 * 定义程序员类
 */
class Programmer{
    private String name;
    public Programmer(String name){
        this.name=name;
    }
 /**
     * 上厕所
     */
    public void wc() {
        synchronized ("pp") {
            try {
                System.out.println("想要上厕所");
                Thread.sleep(500);
                System.out.println("打开厕所门");
                Thread.sleep(500);
                System.out.println("开始上厕所 ");
                Thread.sleep(500);
                System.out.println("排水");
                Thread.sleep(500);
                System.out.println("离开卫生间");
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
        }
    }
}
   
/**
 * 上厕所的线程
 */
class Wc extends Thread{
    private Programmer p;
    public Wc(Programmer p) {
        this.p = p;
    }

    @Override
    public void run() {
        this.p.wc();
    }
}

public class TestSyncThread {
    public static void main(String[] args) {
        
        Programmer p = new Programmer("张三");
        Programmer p1= new Programmer("李四");
        new Wc(p).start();
        new Wc(p1).start();


    }
}


JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术 3414楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/容器(旧) 3415楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 3416楼

老师Scanner为什么会报空指针异常


package internet;


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Scanner;


public class TwoSever {

      public static void main(String[] args) {

      ServerSocket serverSocket = null;

     

try {

serverSocket = new ServerSocket(8888); 

System.out.println("服务端启动,监听端口8888");

Socket socket = serverSocket.accept();

System.out.println("连接成功!");

Thread t= new Thread(new ServiceRead(socket));

Thread t1= new Thread(new ServiceWrite(socket));

t1.start();

t.start();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally {

}

}

}

//接收消息的

class ServiceRead implements Runnable{

    private Socket socket;

    public ServiceRead(Socket socket) {

    this.socket=socket;

    }

@Override

public void run() {

regular();

}

private void regular() {

BufferedReader bu= null;

try {

bu = new BufferedReader(new InputStreamReader(socket.getInputStream()));

   while(true) {

   String str=bu.readLine();

   System.out.println("客户端说:"+str); 

   }

}catch(Exception e) {

e.printStackTrace();

}finally {

try {

if(bu != null) {

bu.close();

}

if(socket != null) {

socket.close();

}

}catch(Exception e) {

e.printStackTrace();

}

}

}

}



//sever发送消息

class ServiceWrite implements Runnable{

    private Socket socket;

   

    public ServiceWrite(Socket socket) {

    this.socket=socket;

    }

@Override

public void run() {

send();

}

private void send() {

Scanner scanner = null;

PrintWriter bw =null;

try {

bw= new PrintWriter(this.socket.getOutputStream());

while(true) {

String str = scanner.nextLine();

    bw.print(str);

    bw.flush();

}

}catch(Exception e) {

e.printStackTrace();

}finally {

try {

if(scanner != null) {

scanner.close();

}

if(bw != null) {

bw.close();

}

if(socket !=null) {

socket.close();

}

}catch(Exception e) {

e.printStackTrace();

}

}

}

}


image.png

JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 3417楼

老师:

  您好,我的代码和运行结果如下:
package com.bjsxt;

public class MyDoublyLinkedList<E> implements MyList<E> {

    /**
     * 定义双向链表中的节点对象
     */
    class Node<E> {
        E item;         //记录元素
        Node<E> prev;   //记录前一个节点对象
        Node<E> next;   //记录下一个节点对象
        Node(Node<E> prev,E item, Node<E> next) {
            this.prev = prev;
            this.item = item;
            this.prev = next;
        }
    }

    private Node head;      //记录头节点
    private Node tail;      //记录尾节点
    private int size;       //记录元素个数

    /**
     * 向双向链表中添加元素
     */
    public void add(E element) {
        this.linkLast(element);
    }

    /**
     * 将节点对象添加到双向链表中的尾部
     */
    private void linkLast(E element) {
        //获取尾节点
        Node t = this.tail;

        //创建节点对象
        Node<E> node = new Node<>(t,element,null);

        //将新节点定义为尾节点
        this.tail = node;
        if(t == null) {
            this.head = node;
        }else {
            t.next = node;
        }
        this.size ++;
    }

    /**
     * 根据指定位置获取元素
     */
    public E get(int index){
        //对index进行合法性校验
        this.checkIndex(index);

        //根据位置查找节点对象
        Node<E> node = this.getNode(index);
        return node.item;
    }
    /**
     * 校验index的合法性
     */
    private void checkIndex(int index) {
        if(!(index >= 0 && index < this.size)) {
            throw new IndexOutOfBoundsException("index:"+index+"Size:"+size);
        }
    }

    /**
     * 根据位置获取指定节点对象
     */
    private Node getNode(int index) {

        //判断当前位置距离头或尾哪个更近些
        if (index < (this.size) >> 1){
            Node node = this.head;
            for(int i=0; i<index; i++) {
                node = node.next;
            }
            return node;
        }else{
            Node node = this.tail;
            for(int i = this.size-1;i>index;i--) {
                node = node.prev;
            }
            return node;
        }
    }

    /**
     * 返回元素的个数
     */
    public int size() {
        return this.size;
    }

    /**
     *  根据指定位置删除元素
     */
    public E remove(int index) {

        //对index进行合法校验
        this.checkIndex(index);

        //根据指定位置获取节点对象
        Node<E> node = this.getNode(index);

        //获取节点对象中的元素
        E item =  node.item;

        //判断节点是否为头节点
        if(node.prev == null) {
            this.head = node.next;
        }else {
            //完成当前节点直接前驱节点与当前节点的直接后继节点的挂接
            node.prev.next = node.next;
        }

        //判断节点是否为尾节点
        if(node.next == null) {
            this.tail = node.prev;
        }else{
            node.next.prev = node.prev;
        }

        //当前节点断掉与它直接前驱节点的连接
        node.prev = null;

        //当前节点断掉与它直接后继节点的连接
        node.next = null;
        node.item = null;

        //记录元素个数
        this.size--;
        return item;
    }

    public static void main(String[] args) {
        MyList<String> myList = new MyDoublyLinkedList<>();
        myList.add("a");
        myList.add("b");
        myList.add("c");
        myList.add("d");
        myList.add("e");

        System.out.println(myList.size());
        System.out.println(myList.remove(0));
        for(int i=0;i<myList.size();i++) {
            System.out.println(myList.get(i));
        }
    }
}

运行结果是:


5

a

b

c

Exception in thread "main" java.lang.NullPointerException

at com.bjsxt.MyDoublyLinkedList.get(MyDoublyLinkedList.java:59)

at com.bjsxt.MyDoublyLinkedList.main(MyDoublyLinkedList.java:150)


JAVA 全系列/第二阶段:JAVA 基础深化和提高/数据结构 3418楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637