Ich habe vor kurzem mit Netzwerkprogrammierung angefangen und bin nun auf das Problem gestoßen, dass entweder mein PrintWriter nicht mehr sendet oder mein Scanner nichts mehr empfängt.
ChatClient.java
ClientThread.java
ChatClient.java
Java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JButton;
public class ChatClient {
JFrame frame;
private JTextField textField;
private JTextPane textPane;
private Socket server;
private PrintWriter out;
public ChatClient(Socket socket, PrintWriter pwout) {
out = pwout;
server = socket;
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textPane = new JTextPane();
textPane.setEditable(false);
textPane.setBounds(10, 10, 415, 200);
frame.getContentPane().add(textPane);
textField = new JTextField();
textField.setBounds(10, 230, 325, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Send");
btnNewButton.setBounds(340, 225, 90, 25);
btnNewButton.addActionListener(new LoginListener());
frame.getContentPane().add(btnNewButton);
}
public class LoginListener implements ActionListener { // Listener ruft die Methode stein() auf.
public void actionPerformed(ActionEvent ev) {
String message = textField.getText();
//out.println(2);
System.out.println(message);
out.println(message);
}
}
}
Java:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ClientThread implements Runnable {
Socket client;
String name;
PrintWriter out;
Scanner in;
public ClientThread(Socket s, String user, Scanner sin, PrintWriter pwout){
System.out.println("2");
client = s;
name = user;
in = sin;
out = pwout;
}
public void sendMessage(String message){
out.println(message);
}
@Override
public void run() {
while(client.isConnected()){
if(in.hasNext()){
String message = in.next();
System.out.println("Broadcasting message: "+message);
Server.broadcast(name, message);
}
}
Server.clients.remove(this);
}
public boolean isConnected(){
return client.isConnected();
}
public String getName(){
return name;
}
}