Well here is the chat code
public class userChat
{
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void chat()
{
JFrame chatFrame = new JFrame("Acidmods Chat");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
outgoing = new JTextField(30);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new sendListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
chatFrame.getContentPane().add(BorderLayout.CENTER, mainPanel);
chatFrame.setSize(600, 400);
chatFrame.setVisible(true);
}
private void setUpNetworking()
{
try
{
sock = new Socket("ip", 6928);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("Networking Established");
}
catch(Exception e)
{
//System.out.print("Error: " + e);
e.printStackTrace();
}
}
public class sendListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
try
{
writer.println(outgoing.getText());
writer.flush();
}
catch(Exception e)
{
System.out.println("Error: " + e);
e.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class IncomingReader implements Runnable
{
public void run()
{
String message;
try
{
System.out.println(reader);
System.out.println(reader.ready());
while((message = reader.readLine()) != null)
{
System.out.println("read" + message);
incoming.append(message + "\n");
}
}
catch(Exception ex)
{
System.out.println("Error: " + ex);
ex.printStackTrace();
}
}
}
}
Message was edited by:
The_Undead
Here's one I prepared earlier. I appologise for the shocking netbeans generated Swing GUI code.
package krc.chat.client;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
/**
* chat.client.ClientForm.java - A wee GUI for a wee chat app.
* @author Keith
*/
public class ClientForm extends javax.swing.JFrame {
private class MessageFetcherator
extends SwingWorker<Void, String>
// The 2nd arg is the type of "intermediate results" to be "published".
{
// doInBackground is invoked in the background thread, it publishes messages
// as they arive to a List of Strings which is then picked up and displayed
// by the process method which runs periodically on the EDT.
@Override
public Void doInBackground() {
MulticastSocket socket = null;
InetAddress address = null;
try {
socket = new MulticastSocket(4446);
address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);
while (!isCancelled()) {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet); //thread blocks here
String response = new String(packet.getData(), 0, packet.getLength());
System.out.println(response);
publish(response);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if(socket!=null)socket.leaveGroup(address);
} catch (Exception e) {
e.printStackTrace();
}
socket.close();
socket = null;
}
return null;
}
// process is invoked in the event dispatch thread whenever swing feels like it
// so it could process several messages at once, but it's safe to mutate the
// swing controls on this thread.
@Override
protected void process(List<String> messages) {
for(String message : messages) {
displayTextArea.append(message+"\n");
}
}
}
private class MessageSenderator {
private String username = null;
private DatagramSocket socket = null;
private InetAddress address = null;
MessageSenderator(String username) throws SocketException, UnknownHostException {
this.username = username.toLowerCase();
this.socket = new DatagramSocket();
this.address = InetAddress.getByName("localhost");
}
public void send(String message) throws IOException {
// send the message
message = username+": "+message;
byte[] bytes = new byte[256];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, this.address, 4447);
byte[] messageBytes = message.getBytes();
packet.setData(messageBytes, 0, messageBytes.length);
this.socket.send(packet);
}
public void close() {
if(socket!=null)socket.close();
}
}
MessageSenderator sender = null;
/** Creates new form ClientForm */
public ClientForm(String username) {
this.setTitle("Chat - "+username);
// build the GUI
initComponents();
// select all the text in the input field and give it focus
inputTextField.setSelectionStart(0);
inputTextField.setSelectionEnd(inputTextField.getText().length());
inputTextField.requestFocus();
try {
sender = new MessageSenderator(username);
sender.send(username+" joins the chat.");
} catch (Exception ex) {
ex.printStackTrace();
}
// setup a background thread which recieves messages from the server
// and appends them to the TextArea on the form.
(new MessageFetcherator()).execute();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
displayTextArea = new javax.swing.JTextArea();
inputTextField = new javax.swing.JTextField();
sendButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
displayTextArea.setColumns(20);
displayTextArea.setFont(new java.awt.Font("Arial", 0, 10));
displayTextArea.setRows(5);
displayTextArea.setTabSize(4);
displayTextArea.setFocusable(false);
jScrollPane2.setViewportView(displayTextArea);
inputTextField.setText("... type your message here ...");
inputTextField.setName("messageText");
inputTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
inputTextFieldActionPerformed(evt);
}
});
sendButton.setText("Send");
sendButton.setName("sendButton");
sendButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(inputTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
sendButtonActionPerformed(evt);
}
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String message = inputTextField.getText();
inputTextField.setText("");
if ("".equals(message.trim())) return;
sender.send(message);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showConfirmDialog(this, e.toString(), "Exception", JOptionPane.ERROR_MESSAGE);
}
}
// Variables declaration - do not modify
private javax.swing.JTextArea displayTextArea;
private javax.swing.JTextField inputTextField;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton sendButton;
// End of variables declaration
}
and here's the client.java ....
package krc.chat.client;
import javax.swing.JOptionPane;
public class Client
{
/**
* Create the GUI and show it.
* For thread safety, this method should be invoked from the event-dispatching thread.
*/
private static void createAndShowGUI(String username) {
new ClientForm(username).setVisible(true);
}
public static void main(String[] args) {
//tell the event-dispatching thread to create & show this application's GUI.
final String username = (args.length==0 ? askUsername() : args[0]);
javax.swing.SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGUI(username); //TODO get username from command line param?
}
}
);
}
private static String askUsername() {
String s = (String)
JOptionPane.showInputDialog(
null
, "username"
, "Enter username"
, JOptionPane.QUESTION_MESSAGE
)
;
return(s==null||"".equals(s) ? "guest" : s);
}
}
Message was edited by: corlettk - frikkin code tags again