Grundsätzlich schreibe ich ein einfaches TCP-UDP-Multiclient-GUI-Programm. Ich kann eine TCP
Verbindung zum Server aber keine UDP
Verbindung herstellen. Der Server lauscht auf Port in 4000.
ich einen comboBox
auf dem GUI-Client, die Elemente hat TCP
und UDP.
Wenn der Benutzer UDP
auswählt und klickt Connect.
Dann wird versucht, durch den Aufruf der Methode UDPconnection
eine UDP
Verbindung herzustellen.Kann keine UDP-Verbindung zwischen einem Client und einem Server herstellen
Hier ist mein Code für die Client-GUI:
public void UDPconnection()
{
try
{
done = false;
datagramSocket = new DatagramSocket(serverPort);
}
catch (SocketException e)
{
done = true;
System.out.println("Host not available");
}
}
Hier ist mein Code für den Chat-Server ist:
public class chatServer2 implements Runnable {
private int clientCount = 0;
private ChatServerThread clients[] = new ChatServerThread[50];
private ServerSocket server = null;
Thread thread = null;
//same as version3
public chatServer2(int port){
try{
server = new ServerSocket(port);//step1
System.out.println("Started the server...waiting for a client");
start(); //the chatserver's start method that goes ahead and creates a new thread
}
catch(IOException e){
System.err.println("ERROR "+e.getMessage());
}
}
public void start(){
if(thread == null){
thread = new Thread(this);
thread.start();
}
}
@Override
public void run() {//same as version 3
while(thread !=null){
try{
System.out.println("Waiting for a client...");
//now we add a new Thread and accept a client
addThread(server.accept());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void addThread(Socket socket){
if(clientCount < clients.length){
clients[clientCount] = new ChatServerThread(this, socket);
try {
clients[clientCount].open();//open the stream for the ChatServerThread client
clients[clientCount].start();//start to run the ChatServerThread client
clientCount++;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void handle(int ID, String input)
{
System.out.println(input);
if(input.equalsIgnoreCase("bye"))
{
remove(ID);//person said bye so remove them
}
else
{
System.out.println(input);
for (int i = 0; i < clientCount; i++)
{
clients[i].send("User: " + ID + ": " + input);
}
}
}
public synchronized void remove(int ID){
int position = findClient(ID);
if(position >=0){
ChatServerThread toRemove = clients[position];
if(position <clientCount-1){
for(int i= position+1; i <clientCount; i++){
clients[i-1] = clients[i];
}
clientCount--;
}
try {
toRemove.close();//close the person's that said bye connection
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private int findClient(int ID){
for(int i=0; i<clientCount; i++){
if(clients[i].getID() == ID){
return i;
}
}
return -1;//not in the array
}
public static void main(String [] args){
chatServer2 l = new chatServer2(4000);
}
}