我正在编写一个小客户端 - 服务器应用程序,但存在以下问题:
我可以毫无问题地启动服务器,但是当我尝试与客户端连接时,它说连接被拒绝:连接
谷歌和搜索说我使用了错误的端口,但我在服务器和客户端使用相同的端口。我在代码中找不到任何错误,不知道为什么它不起作用。
这是代码:
服务器
public class Server extends JFrame implements Runnable {
private JPanel contentPane;
private JTextField textFieldPort;
private JTextField textFieldMessage;
private ArrayList<Handler> activeUsers;
private List listUsers;
private ServerSocket listen;
private Thread connect;
private List listProtocoll;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Server frame = new Server();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Server() {
setTitle("Server");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPort = new JLabel("Port:");
lblPort.setBounds(10, 11, 24, 14);
contentPane.add(lblPort);
textFieldPort = new JTextField();
textFieldPort.setBounds(44, 8, 114, 20);
contentPane.add(textFieldPort);
textFieldPort.setColumns(10);
JButton buttonStart = new JButton("start");
buttonStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startServer();
}
});
buttonStart.setBounds(168, 7, 89, 23);
contentPane.add(buttonStart);
listProtocoll = new List();
listProtocoll.setBounds(10, 44, 368, 250);
contentPane.add(listProtocoll);
textFieldMessage = new JTextField();
textFieldMessage.setBounds(10, 300, 267, 20);
contentPane.add(textFieldMessage);
textFieldMessage.setColumns(10);
JButton btnSend = new JButton("send");
btnSend.setBounds(289, 300, 89, 23);
contentPane.add(btnSend);
listUsers = new List();
listUsers.setBounds(404, 44, 120, 214);
contentPane.add(listUsers);
JButton btnKick = new JButton("kick");
btnKick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
kickUser();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnKick.setBounds(414, 264, 89, 23);
contentPane.add(btnKick);
}
/**
* Methods
*
* @throws IOException
*/
private void startServer() {
if (!textFieldPort.getText().toString().trim().equals("")) {
try {
listen = new ServerSocket(Integer.valueOf(
textFieldPort.getText()).intValue());
connect = new Thread(this);
connect.start();
listProtocoll.add("Server started.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void listen() {
while (true) {
try {
Socket socket = listen.accept();
Thread t = new Thread(new Handler(this, socket));
t.start();
} catch (Exception e) {
System.err.print("Fehler.");
}
}
}
protected void broadcast(String message) throws IOException {
// TODO: broadcast-method
for (Handler handler : activeUsers) {
handler.sendMessageToClient(message);
}
}
protected boolean checkName(String name) {
for (Handler handler : activeUsers) {
if (handler.getClientname() == name) {
return false;
}
}
return true;
}
protected void addUser(Handler newClient) throws IOException {
// TODO: add new user to activeUsers
activeUsers.add(newClient);
refreshList();
sendUserList();
broadcast("MSG¿" + newClient.getClientname() + " joined the chat.");
}
protected void removeUser(Handler removingClient) {
// TODO: remove
int index = 0;
for (Handler handler : activeUsers) {
if (handler == removingClient) {
activeUsers.remove(index);
}
index++;
}
try {
refreshList();
sendUserList();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void kickUser() throws IOException {
// TODO: kick selected user from chat and broadcast kick-message
activeUsers.remove(listUsers.getSelectedIndex());
refreshList();
sendUserList();
broadcast("user " + activeUsers.get(listUsers.getSelectedIndex())
+ " has been kicked.");
}
private void refreshList() {
for(Handler handler: activeUsers) {
listUsers.add(handler.getClientname());
}
}
private void sendUserList() throws IOException {
// TODO: get the names from all active clients and build a String("USR"
// + "¿" + name1 + "¿" + name2...)
// TODO: broadcast built String
String listString = "USR¿";
for (Handler handler : activeUsers) {
listString = listString + handler.getClientname() + "¿";
}
broadcast(listString);
}
@Override
public void run() {
// TODO Auto-generated method stub
listen();
}
}
的处理程序
public class Handler implements Runnable {
private DataInputStream in;
private DataOutputStream out;
private Socket socket;
private Server server;
private Date time;
private String[] split;
private String clientname;
public Handler(Server server, Socket socket) throws IOException {
this.socket = socket;
if (in == null) {
in = new DataInputStream(socket.getInputStream());
}
if (out == null) {
out = new DataOutputStream(socket.getOutputStream());
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
receiveMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void receiveMessage() throws IOException {
// TODO Auto-generated method stub
String inMessage = in.readUTF();
while (in.readUTF() != null) {
inMessage = in.readUTF();
split = inMessage.split("¿");
if(split[0].equals("NIC")) {
if(server.checkName(split[2])) {
this.clientname = split[2];
server.addUser(this);
}
}
if(split[0].equals("MSG")) {server.broadcast(buildMessage(inMessage));}
if(split[0].equals("BYE")) {disconnect();}
if(split[0].equals("help")){sendCommands();}
}
}
private void sendCommands() throws IOException {
sendMessageToClient("MSG" + "¿" + "help = show all available commands.");
sendMessageToClient("MSG" + "¿" + "bye = disconnect from server.");
}
private void disconnect() throws IOException {
server.removeUser(this);
socket.close();
socket.shutdownInput();
socket.shutdownOutput();
socket = null;
}
private String buildMessage(String message) {
// TODO: build message with time and parameter-message
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
time = new Date();
String newMessage = "" + formatter.format(time) + " " + message;
return newMessage;
}
public String getClientname() {
return this.clientname;
}
protected void sendMessageToClient(String message) throws IOException {
// TODO Auto-generated method stub
out.writeUTF(message);
}
}
的客户端
public class Client extends JFrame implements Runnable {
private JPanel contentPane;
private JTextField textFieldIp;
private JTextField textFieldPort;
private JTextField textFieldMessage;
private String message;
private DataInputStream in;
private DataOutputStream out;
private Socket socket;
private List listProtocoll;
private JLabel lblName;
private JTextField textFieldName;
private String name;
private String ip;
private int port;
private List listUsers;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Client frame = new Client();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*
* @throws IOException
*/
public Client() throws IOException {
setTitle("Chat");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 549, 350);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblIp = new JLabel("IP:");
lblIp.setBounds(10, 11, 14, 14);
contentPane.add(lblIp);
textFieldIp = new JTextField();
textFieldIp.setBounds(34, 8, 86, 20);
contentPane.add(textFieldIp);
textFieldIp.setColumns(10);
JLabel lblPort = new JLabel("Port:");
lblPort.setBounds(130, 11, 29, 14);
contentPane.add(lblPort);
textFieldPort = new JTextField();
textFieldPort.setBounds(169, 8, 106, 20);
contentPane.add(textFieldPort);
textFieldPort.setColumns(10);
JButton btnConnect = new JButton("connect");
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnConnect.setBounds(434, 7, 89, 23);
contentPane.add(btnConnect);
listProtocoll = new List();
listProtocoll.setBounds(10, 54, 391, 204);
contentPane.add(listProtocoll);
listUsers = new List();
listUsers.setBounds(413, 55, 110, 203);
contentPane.add(listUsers);
textFieldMessage = new JTextField();
textFieldMessage.setBounds(10, 281, 384, 20);
contentPane.add(textFieldMessage);
textFieldMessage.setColumns(10);
Button button = new Button("send");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage(buildMessage("MSG"));
}
});
button.setBounds(413, 281, 70, 22);
contentPane.add(button);
lblName = new JLabel("Name:");
lblName.setBounds(285, 11, 46, 14);
contentPane.add(lblName);
textFieldName = new JTextField();
textFieldName.setBounds(325, 8, 99, 20);
contentPane.add(textFieldName);
textFieldName.setColumns(10);
}
/***
* Methods
*
* @throws IOException
* @throws UnknownHostException
*/
private void connect() throws UnknownHostException, IOException {
// TODO: connect body
this.name = textFieldName.getText().toString().trim();
this.ip = textFieldIp.getText().toString().trim();
this.port = Integer.valueOf(textFieldPort.getText().trim()).intValue();
System.out.println("trying to connect to Server " + ip + " / " + port);
socket = new Socket(ip, port);
if (in == null) {
in = new DataInputStream(socket.getInputStream());
}
if (out == null) {
out = new DataOutputStream(socket.getOutputStream());
}
out.writeUTF("NIC" + "¿" + textFieldName.getText().toString().trim());
System.out.println("Successfully connected!" + "\n");
}
protected void disconnect() throws IOException {
// TODO: disconnect body
socket.close();
socket.shutdownInput();
socket.shutdownOutput();
}
protected void showMessage(String message) {
// TODO: add message to protocol-list
listProtocoll.add(message);
listProtocoll.makeVisible(listProtocoll.getItemCount() - 1);
}
private void sendMessage(String capital) {
// TODO: send message to server which broadcasts the message
try {
out.writeUTF(buildMessage(capital));
} catch (Exception e) {
System.err.print(e);
}
}
private String buildMessage(String capital) {
// TODO: build message with nickname and text
// the following code should be in the Server-class
// if (textFieldName.getText().toString().trim() == "help") {
// showCommands();
// }
// if (textFieldName.getText().toString().trim() == "exit") {
// disconnect();
// }
message = capital + "¿" + textFieldName.getText().toString() + ": "
+ textFieldMessage.getText().toString();
return message;
}
protected void receiveMessage() throws Exception {
// TODO: wait for incoming message then call showMessage()
message = in.readUTF();
while (in.readUTF() != null) {
message = in.readUTF();
checkMessage(message);
}
}
private void checkMessage(String message) {
String[] split = message.split("¿");
if (split[0].equals("USR")) {
refreshUserlist(split);
}
if (split[0].equals("MSG")) {
showMessage(split[1]);
}
}
public String getName() {
return this.name;
}
private void refreshUserlist(String[] newList) {
listUsers.removeAll();
for (int i = 1; i < newList.length; i++) {
listUsers.add(newList[i]);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
receiveMessage();
} catch (Exception e) {
System.err.print(e);
}
}
}
答案 0 :(得分:0)
附加到0.0.0.0
(所有网络接口)而不是特定主机名或IP号。