RSS

Java Networking

24 Jun

This week has been a busy one. I checked up on a lot of stuff majorly to do with Networking in Java. Below is the code for a chat app. I shall also provide links to some great resources. I do hope to add more features, currently improving it and then try file transfer.

<blockquote>/*ServerSide.java
* This is will be on the server and will always be running(its on an infinitive loop).
* The server accepts a client and in a new thread initializes a client socket for it.
* The clients 'PrintWriter' are stored in an array. When a client sends a message the message is received
* by the server and distributed through the PrintWriter's in the array.
*
*
*
*/

package com.gilo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;

public class ServerSide {
ArrayList&lt;PrintWriter&gt; cos; //Array of ClientOutputStreams

public class clientHandler implements Runnable{
BufferedReader reader;
Socket sock;

public clientHandler(Socket clientSocket){
try{
sock = clientSocket;
InputStreamReader isr = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isr);

}catch(IOException e){
e.printStackTrace();
}

}

public void run(){
String message;

try{
while((message = reader.readLine()) != null){
telleveryone(message);
}

}catch(IOException err){
err.printStackTrace();
}
}

private void telleveryone(String message){
Iterator itr = cos.iterator();
while(itr.hasNext()){
PrintWriter pWriter = (PrintWriter) itr.next();
pWriter.println(message);
pWriter.flush();
}

}
}

public static void main(String args[]){
new ServerSide().createSocket();
}

public void createSocket(){
cos = new ArrayList&lt;PrintWriter&gt;();

try{
ServerSocket socket = new ServerSocket(5000);

while(true){
Socket clientSocket = socket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
cos.add(writer);

Thread t = new Thread(new clientHandler(clientSocket));
t.start();
}

}catch(IOException err){
System.out.println("ERROR: " + err.getMessage());
}

}

}</blockquote>

And the clientSide:

<blockquote>/*
* ClientSide.java
*
* The client socket takes in an ip address of the server as one of the arguments and the port
* Since I would test it on my own computer the ip provided is my computer's, so before running it change the ip.
* on cmd type on 'ipconfig' to get your computer's ip (look for something like ipv4 or 6 depending on the region you come from)
* on linux 'ifconfig' at the terminal will do.
*
*/

package com.gilo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class ClientSide extends JFrame{

JTextField outgoing;
JTextArea incoming;
BufferedReader reader;
PrintWriter writer;
Socket sock;
String username;

public ClientSide(){
super("Chat");
JPanel mainpanel = new JPanel();
incoming = new JTextArea(15,25);
incoming.setLineWrap(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

outgoing = new JTextField(20);

outgoing.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
writer.println(username + " - " + e.getActionCommand());
writer.flush();

outgoing.setText("");
}catch(Exception err){
JOptionPane.showMessageDialog(null, "Error! Could not send the message \n"+err.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
});
JButton sendButton = new JButton("send");
sendButton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
writer.println(username + " - " + outgoing.getText());
writer.flush();

outgoing.setText("");
}catch(Exception err){
JOptionPane.showMessageDialog(null, "Error! Could not send the message \n"+err.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
});
mainpanel.add(qScroller);
mainpanel.add(outgoing);
mainpanel.add(sendButton);

setupNetworking(); //Sockets and connections are established here

Thread readerThread = new Thread(new IncomingReader());
readerThread.start();

getContentPane().add(BorderLayout.CENTER,mainpanel);

setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void setupNetworking(){
try{
sock = new Socket("10.223.73.199",5000); //Change the ip address to one of your comp. see above for details
InputStreamReader isR = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isR);
writer = new PrintWriter(sock.getOutputStream());

username =System.getProperty("user.name");
username =(String) JOptionPane.showInputDialog(null,"Username: ","Info",JOptionPane.INFORMATION_MESSAGE,null,null,username );

writer.println(username +" - " + " has joined the chat");
writer.flush();

}catch(UnknownHostException e){
e.printStackTrace();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error - Unable to connect to server \n " + e.getMessage(), "Error" , JOptionPane.ERROR_MESSAGE);

}
}

public static void main(String args[]){
ClientSide cs = new ClientSide();
}

public class IncomingReader implements Runnable{
public void run(){
String message;
try {
while((message=reader.readLine()) != null){
incoming.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}</blockquote>
Advertisements
 
2 Comments

Posted by on June 24, 2012 in Code, Java

 

Tags: ,

2 responses to “Java Networking

  1. Harrison

    January 20, 2013 at 9:07 pm

    wow!great postings on code.liking it

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: