...

View Full Version : TCP/IP Client-Server Chat Program



thornt5748
01-12-2012, 05:02 PM
Hi Guys,

I'm quite new here and am new to Java Programming, but i could use some help. I have a client-serve chat program and have almost finished it to my standards however I am trying to enable the server to accept multiple clients, how would i do this? what do i have to add or change on the server to allow this?

Server


import java.awt.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;

public class SwingChatServer extends SwingChatGUI
{
public String outline;
public String fromClient, s = "";
PrintWriter out;
BufferedReader in;
BufferedReader stdin;
String inputLine, outputLine;
public ButtonHandler bHandler = new ButtonHandler();

public SwingChatServer (String title)
{
super (title);
bHandler = new ButtonHandler ();
sendButton.addActionListener (bHandler);
}

private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
outputLine = txArea.getText ();
System.out.println ("Server :> " + outputLine);
out.println (outputLine);
outline = txArea.getText ();
s = "Server :>"+ outline+"\n";
rxArea.append(s);
txArea.setText("");
}
}

public void run () throws IOException
{
ServerSocket serverSocket = null;

try
{
serverSocket = new ServerSocket (4444);
}
catch (IOException e)
{
System.err.println ("Could not listen on port: 4444.");
System.exit (1);
}

Socket clientSocket = null;
try
{
clientSocket = serverSocket.accept ();
}
catch (IOException e)
{
System.err.println ("Accept failed.");
System.exit(1);
}

out = new PrintWriter (clientSocket.getOutputStream (), true);
in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
//stdin = new BufferedReader (new InputStreamReader (System.in));

out.println ("Welcome to the Chat Server");


while ((fromClient = in.readLine ()) != null) //allows a new line to not over write the chat
{
System.out.println ("Client :> " + fromClient);
s = "Client :>" + fromClient + "\n";
rxArea.append (s);

if (fromClient.equals ("Bye"))System.exit(0);

}

out.close();
in.close();
clientSocket.close();
serverSocket.close();
}

public static void main(String[] args) //throws IOException
{

SwingChatServer frame = new SwingChatServer ("Chat Server Program");

frame.pack ();
frame.setVisible(true);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("chat.jpg"));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
try
{
frame.run ();
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to: 194.81.104.118!\n");
System.exit(1);
}

}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum