会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132838个问题

package com.bjsxt.client;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
 
/**
 * 客户端(做好准备与服务器端通信),以字节流作为传输方式
 * @author Administrator
 *
 */
public class TestClient {
    public static void main(String[] args) throws UnknownHostException, IOException {
        //新建socket对象
        Socket client = new Socket("127.0.0.1",9999);
         
        //新建输出流对象(因为要给服务器端发送消息,所以得有输出流对象)
        OutputStream os = client.getOutputStream();
    //  os.write("来自客户端的请求:abc".getBytes());
        os.write("来自服务器的请求:abc".getBytes());
         
        //打印一句话表明,客户端已发出请求
        System.out.println("---客户端已发出请求---");
         
        //新建输入流对象(从服务器端接收消息,所以得有输入流对象,相当于从服务器端读取内容)
        InputStream is = client.getInputStream();
        //将读到的输入的内容存储,并打印
        byte[] buf = new byte[1024];
        int len =0;
        while((len=is.read(buf))!=-1) {
            System.out.println(new String(buf,0,len));
        }
         
        //关闭流
        if(is!=null) {
            is.close();
        }
        if(os!=null) {
            os.close();
        }
    }
 
}

Error:(19, 32) java: 无法将类 com.sun.org.apache.xpath.internal.operations.String中的构造器 String应用到给定类型;

  需要: 没有参数

  找到: byte[],int,int

  原因: 实际参数列表和形式参数列表长度不同

老师这是什么原因呀

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

为什么我这个生产者只生产娃哈哈 , 而且 后面的null值是怎么回事儿?

public class Goods {
    private String name;//商品名字
    private String brand;//

    public Goods() {
    }

    public Goods(String name, String brand) {
        this.name = name;
        this.brand = brand;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public String getBrand() {
        return brand;
    }
    //编写一个赋值方法,同步监视器就为当前对象
    public synchronized void set(String nane ,String brand) throws InterruptedException {
        this.setName(name);
        Thread.sleep(300);
        this.setBrand(brand);
        System.out.println("生产者线程生产了:"+this.getBrand()+"---"+this.getName());
    }
    public synchronized void get ()throws InterruptedException{
        System.out.println("消费者线程取走了:"+this.getBrand()+"---"+this.getName());
    }
}

结果:

/**

生产者线程生产了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
消费者线程取走了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null
生产者线程生产了:娃哈哈---null

Process finished with exit code 0

*/


JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术(旧) 3036楼

老师,我按照视频上老师的方法敲了代码,运行都没问题,但是突然发现,这个程序并没有自动结束,IDEAL中的红色方块一直亮着,如下图:

0f6ec0316320147f37a1f9cdcf5e5f5.png

麻烦老师帮忙看看是怎么回事,具体代码粘贴如下:

1.Printer类代码

package com.bjsxt.thread;

public class Printer {
    private int index=1;//用于统计第几次打印
    public synchronized void print(int number){
        while(index%3==0){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print(number);
        index++;
        super.notifyAll();//唤醒所有在printer这个对象上所有等待的线程
    }
    public synchronized void print(char letter){
        while(index%3!=0){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print(""+letter);
        index++;
        super.notifyAll();
    }
}

2.数字打印类代码

package com.bjsxt.thread;

public class NumberPrinter implements Runnable {
    private Printer printer;

    public NumberPrinter(Printer printer) {
        this.printer=printer;
    }

    @Override
    public void run() {
        for(int i=1;i<=52;i++){
            printer.print(i);
        }
    }
}

3.字母打印类代码

package com.bjsxt.thread;

public class LetterPrinter implements Runnable{
    private Printer printer;
    public LetterPrinter(Printer printer){
        this.printer=printer;
    }    @Override
    public void run() {
        for(char c='A';c<='z';c++){
          printer.print(c);
        }
    }
}

4.主线程测试代码

package com.bjsxt.thread;

public class Test {
    public static void main(String[] args) {
        //创建共享资源的对象
        Printer p=new Printer();
        NumberPrinter np=new NumberPrinter(p);
        LetterPrinter lp=new LetterPrinter(p);
        //创建代理类,并启动线程
        new Thread(np).start();
        new Thread(lp).start();
    }
}


JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程和并发编程(旧) 3037楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术 3038楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 3040楼

image.png

package com.bjsxt.copy;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestCopy {
	public static void main(String[] args) {
		File srcDir=new File("D:\\信息");
		File targetDir=new File("D:\\信息");
		copyDir(srcDir, targetDir);
	}
	public static void copyDir(File srcDir,File targetDir){
		if(!targetDir.exists()){
			targetDir.mkdir();
		}
		File []files=srcDir.listFiles();
		for(File file : files){
			if(file.isFile()){
				copyFile(new File(srcDir+"\\"+file.getName()),new File(targetDir+"\\"+file.getName()) );
				
			}
			else{
				copyFile(new File(srcDir+"\\"+file.getName()),new File(targetDir+"\\"+file.getName()) );
				
			}
		}
	}
	public static void copyFile(File src,File target){
		
		//提高读取速率。从数据源
		BufferedInputStream bis=null;
		//提高写入效率,写到目的地
		BufferedOutputStream bos=null;
		try {
			bis = new BufferedInputStream(new FileInputStream(src));
			bos = new BufferedOutputStream(new FileOutputStream(target));
			//边读边写
			byte [] buf=new byte[1024];
			int len=0;
			while((len=bis.read())!=-1){
				bos.write(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//关闭
			if(bis!=null){
				try {
					bis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(bos!=null){
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
	
	} 
}

为什么会出现文件无法访问啊!什么原因引起的,我这个文件夹里只放了一个文档文件!

JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 3041楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/常用类 3043楼

package com;

//接收客户端发送消息的线程类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class ChatReceive extends Thread{
    private Socket socket;
    public ChatReceive(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        super.run();
    }

    //实现接收客户端发送的消息
    private void receiveMsg(){
        BufferedReader nb = null;
        try {
            nb = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while (true){
                String msg = nb.readLine();
                synchronized ("abc"){
                    //把读取到的数据写入公共数据区
                    CharRoomServer.buf="["+this.socket.getInetAddress()+"]"+msg;
                    //唤醒发送消息的线程对象
                    "abc".notifyAll();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (nb!=null){
                try {
                    nb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (this.socket!=null){
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//xiang客户端发送消息的线程类

class ChatSend extends Thread{
    private Socket socket;
    public ChatSend(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        sendMsg();
    }


    //将公共数据区的消息发送给客户端

    private void sendMsg(){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(this.socket.getOutputStream());
            while (true){
                synchronized ("abc"){
                    //让发送消息的线程处于等待状态
                    "abc".wait();
                    //将公共数据区的消息发送给客户端
                    pw.println(CharRoomServer.buf);
                    pw.flush();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (pw!=null){
                pw.close();
            }
            if (this.socket!=null){
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class CharRoomServer {
    //定义公共数据区
    public static String buf;
    public static void main(String[] args)  {
        System.out.println("Chat Server Version 1.0");
        System.out.println("Listen at 8888");
        ServerSocket serverSocket = null;
        try {
            while (true){
                Socket socket = serverSocket.accept();
                System.out.println("连接到:"+socket.getInetAddress());
                new ChatReceive(socket).start();
                new ChatSend(socket).start();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

"C:\Program Files\Java\jdk-15.0.1\bin\java.exe" -Didea.launcher.port=51224 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Users\Administrator\IdeaProjects\socketDemo\out\production\socketDemo;C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMainV2 com.CharRoomServer

Chat Server Version 1.0

Listen at 8888

java.lang.NullPointerException: Cannot invoke "java.net.ServerSocket.accept()" because "serverSocket" is null

at com.CharRoomServer.main(CharRoomServer.java:111)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:564)

at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)


Process finished with exit code 0





找不到解决方法来

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

课程分类

百战程序员微信公众号

百战程序员微信小程序

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