gpt4 book ai didi

java - 服务器端Java错误

转载 作者:行者123 更新时间:2023-12-02 07:26:19 25 4
gpt4 key购买 nike

我编写了一个程序,从电话(Java ME)向服务器发送一条消息“测试”。但我在尝试在服务器端调用 closeCrap() 方法时遇到错误。

错误日志:

Exception in thread "main" java.lang.NullPointerException
at server.closeCrap(server.java:106)
at server.startRunning(server.java:55)
at pagr.main(pagr.java:7)

服务器.java

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class server extends JFrame{
private static final long serialVersionUID = 1L;
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
// constructor
public server(){
super("CP Chat");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
// nusius teksta ivesta
userText.setText("");
}
}
);
add(userText,BorderLayout.NORTH);
chatWindow = new JTextArea();
chatWindow.setEditable(false);
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);
}
// set up and run a server
public void startRunning(){
try{
// 1 arg - jungiasi prie port (gali buti betkoks)
//2 - backLog (kiek zmoniu gali prisijungti prie port)
server = new ServerSocket(6789,100);
while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException exc){ // end of stream
showMessage("\n Server ended the connection!");
}finally{
closeCrap();
}
}
}catch(IOException ex){
ex.printStackTrace();
}
}
// wait for connection, then display connection info
private void waitForConnection() throws IOException{
showMessage("Waiting for someone to connect... \n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
// get stream to send and receive data
private void setupStreams() throws IOException{
//creating path way to connect to another computer.
output = new ObjectOutputStream(connection.getOutputStream());
// flushes any left overs to the other pc while sending messages
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are now setup!\n");
}
//during the chat conversation
private void whileChatting() throws IOException{
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do{
try{
// gauna atsiunciama zinute
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException notFound){
showMessage("\n idk wtf that user send!");
}
}while(!message.equals("CLIENT - END"));
}
//close Streams and Sockets after youre done chatting
private void closeCrap(){
showMessage("\n Closing connection... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException except){
except.printStackTrace();
}
}
private void sendMessage(String message){
try{
// sends a message to client
output.writeObject("SERVER - " + message);
// if something is left - flush those bytes to the client.
output.flush();
showMessage("\n SERVER - " + message);
}catch(IOException e){
chatWindow.append("\n ERROR: dude i cant send that message");
}
}
// updates chat window
private void showMessage(final String text){
// creates a thread that will update a part of GUI
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
//add message to the end of the document
//and it updates the chat window
chatWindow.append(text);
}
}
);
}
// let the user type something in the text field
// final type - cant be modified
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}

play.java(手机上)

import java.util.Random;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;
public class play extends GameCanvas {
StreamConnection connection;
PrintStream output;
InputStream in;
public play(){
super(false);
setFullScreenMode(true);
}
public void start(){
try{
connection();
setupStreams();
}catch(EOFException ex){
}catch(IOException exc){
exc.printStackTrace();
}finally{
closeCrapi();
}
}
private void connection() throws IOException{
StreamConnection connection = (StreamConnection)Connector.open("socket://127.0.0.1:6789");
in = connection.openInputStream();
}
private void setupStreams() throws IOException{
PrintStream output = new PrintStream(connection.openOutputStream());
output.println("Test");
output.flush();
}
private void closeCrapi(){
try{
output.close();
in.close();
connection.close();
}catch(IOException ex){}
}
}

编辑:我更改了用户 Endox 告诉我的内容,但出现错误:

java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)
at java.io.ObjectOutputStream.<init>(Unknown Source)
at server.setupStreams(server.java:75)
at server.startRunning(server.java:50)
at pagr.main(pagr.java:7)
Exception in thread "main" java.lang.NullPointerException
at server.closeCrap(server.java:107)
at server.startRunning(server.java:56)
at pagr.main(pagr.java:7)

EDIT2 我将 if 语句添加到 close crap 方法中:在关闭输出之前,它检查该对象是否不为空。新错误:

java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at server.setupStreams(server.java:77)
at server.startRunning(server.java:50)
at pagr.main(pagr.java:7)

最佳答案

在此循环中:

while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException exc){ // end of stream
showMessage("\n Server ended the connection!");
}finally{
closeCrap();
}
}

如果waitForConnection()抛出EOFException,您将直接进入finally block (在显示消息之后)。 setupStreams() 没有调用任何更改,因此导致此行中出现 NullPointerException(在 closeCrap() 内部):

output.close();

关于java - 服务器端Java错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13550810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com