我正在尝试Socket
用 Java 发送图像,但是我得到了NullPointerException
. 这是服务器的代码:
package sendImage;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class Server {
ServerSocket server;
Socket client;
//------------------------------------------------------------------------------
public static void main(String[] args) {
new Server();
}
//------------------------------------------------------------------------------
public Server(){
connect();
}
//------------------------------------------------------------------------------
public void connect(){
try{
server = new ServerSocket(9999);
client = server.accept();
sendImage();
}catch(Exception e){
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
public void sendImage(){
String image = "C:/Users/JavaChild/Downloads/jo-d-101027-mentalist.jpg";
try{
InputStream in = Server.class.getResourceAsStream(image);
BufferedImage img = ImageIO.read(in);
JLabel l = new JLabel(new ImageIcon(img));
JFrame frame = new JFrame("Server");
frame.add(l);
frame.setVisible(true);
ImageIO.write(img, "JPG", client.getOutputStream());
}catch(Exception e){
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
}
和客户:
package sendImage;
import java.net.*;
import javax.imageio.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.image.BufferedImage;
import java.io.*;
public class Client {
Socket server;
//------------------------------------------------------------------------------
public static void main(String[] args) {
new Client();
}
//------------------------------------------------------------------------------
public Client(){
connect();
}
//------------------------------------------------------------------------------
public void connect(){
try{
server = new Socket("JavaChild-PC",9999);
readImage();
}catch(Exception e){
e.printStackTrace();
}
}
//------------------------------------------------------------------------------
public void readImage(){
try{
BufferedImage img = ImageIO.read(server.getInputStream());
JLabel label = new JLabel(new ImageIcon(img));
JFrame frame = new JFrame("Client");
frame.add(label);
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
}
请告诉我如何通过套接字正确发送图像
以及导致异常的原因是什么?
堆栈跟踪
java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at sendImage.Client.readImage(Client.java:37)
at sendImage.Client.connect(Client.java:28)
at sendImage.Client.<init>(Client.java:22)
at sendImage.Client.main(Client.java:18)