Ich habe zwei einfache Java-Programme gemacht: Server-Chat und Client-Chat. Ich sehe keine Fehler in den Codes jeder Java-Datei, aber die Programme hängen, wenn ich versuche, das Client-Programm mit dem Server-Programm zu verbinden. HierJava Chat-Programm (Server und Client) hängt und nichts passiert,
ist der Server-Side-Code:
package com.server;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection = null;
/**
* Creates new form sever
*/
public Server() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
startRunning();
}
//setup and run the server
public void startRunning(){
try{
//serversocket(port,queueLength)
server = new ServerSocket(6789, 100);
while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Server ended the connection!");
}finally{
closeCrap();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection
private void waitForConnection() throws IOException{
showMessage("Waiting for someone to connect...\n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress());
}
//get stream to send and receive data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
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 = "SERVER - You are now connected! ";
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classNotfoundException){
showMessage("\n idk wtf the user sent!");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets after chatting
private void closeCrap(){
showMessage("\n Closing connections...\n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}catch(NullPointerException nullPointerException){
showMessage("You are trying to close something not opened");
}
}
//send message to clients
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSEVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n Error: i cant send that message");
}
}
//updates chatWindow
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
//let the user type stuff
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
}
Und hier ist der Client-Seite Code:
package com.client;
import javax.swing.JOptionPane;
import java.sql.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
public class client extends javax.swing.JFrame {
Connection con;
int b;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP = "127.0.0.1";
private Socket connection;
public client() {
initComponents();
}
private void statusMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
startRunning();
}
//start chat system
public void startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
eofException.printStackTrace();
showMessage("\n Client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeCrap();
}
}
//connect to server
private void connectToServer() throws IOException{
showMessage("\nAttempting connection...\n");
try{
connection = new Socket(InetAddress.getByName(serverIP),6789);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}catch(ConnectException connectException){
showMessage("IP not available or port busy");
}
}
//streams for seding and receiving
private void setupStreams() throws IOException{
try{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are good to go \n");
}catch(Exception e){
System.out.println("there was error with output or input");
}
}
//while chatting with server
private void whileChatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
System.out.println(message);
}catch(ClassNotFoundException classNotfoundException){
showMessage("\n I dont know what that object is");
}catch(EOFException eofException){
showMessage("\nThere was an error with collecting input ");
}
}while(!message.equals("SERVER - END"));
}
//clos all stuff
private void closeCrap() {
showMessage("\n Closing connection...");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n Something went wrong while sending message");
}
}
//showMessages
private void showMessage(final String m){
java.awt.EventQueue.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(m);
}
}
);
}
//allow typing
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
//showError
private void showError(String err){
String errMsg = err;
JOptionPane.showMessageDialog(null, errMsg, "Error", JOptionPane.ERROR_MESSAGE);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new client().setVisible(true);
}
});
}
Ich werde sehr froh sein, wenn jemand durch gehen könnte und geben Sie mir einige Hinweise, wie man das korrigiert.
Dies kann auch einfach sein, aber haben Sie eine Firewall auf? – DejaVuSansMono
Haben Sie versucht, einen Debugger zu verwenden, um zu sehen, wo genau das Problem liegt? –
Wohin genau beginnt Ihr Server den Port zu hören? Sie haben eine fehlende 'initComponents()' Methode, die Sie uns nicht gegeben haben. – RealSkeptic