Reputation: 167
i am just programming a multiplayer java game and i tried to write a server. But every time i start it, It simply dosen't work and eclipse is not even giving me an error message. I found out that the error must be at this line: Socket sock = serverSock.accept(); Can anyone see the mistake?
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Frame {
JFrame frame;
JPanel panel;
JButton start;
JLabel status;
public Frame() {
frame = new JFrame("Server");
panel = new JPanel();
start = new JButton("Start");
status = new JLabel("Server is not running.");
start.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
try {
ServerSocket serverSock = new ServerSocket(5000);
Socket sock = serverSock.accept();
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
BufferedReader reader = new BufferedReader(isReader);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
status.setText("Server is running.");
status.setForeground(Color.green);
start.setText("Stop");
}});
status.setForeground(Color.RED);
frame.setVisible(true);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(panel);
panel.add(start);
panel.add(status);
}
}
Thanks Lennart
Upvotes: 0
Views: 119
Reputation: 159874
One source of error here is the fact that you're blocking the EDT
. Swing is single-threaded so any process heavy or blocking calls, such as ServerSocket#accept()
, will freeze your UI. Here you could use a SwingWorker instead.
Also when you do implement SwingWorker
, you will need to use your BufferedReader
to read data from the client. Currently no client data is being displayed.
Upvotes: 1