Facebook Twitter Gplus E-mail RSS
 
 
Home » Java » Java Socket Programming – Simple Client/Server Chat Program
formats

Java Socket Programming – Simple Client/Server Chat Program

Published on February 24th, 2010 by in Java

Open up the two java programs given below (SimpleServer & SimpleClient) using your JAVA IDE (I prefer JCreator) separately. Buid it and run the SimpleServer 1st then run SimpleClient. Now start chating.

SimpleServer

SimpleClient

SimpleServer Source Code:



import java.net.*;
import java.io.*;
import java.util.*;
import java.text.DateFormat;
public class SimpleServer {
public static void main(String args[]) {
ServerSocket s = null;

//Input From Keyboard
String str;
DataInputStream indata= new  DataInputStream (System.in);
System.out.println(“Type in Something & Press Enter to Send it To The >>C L I E N T<<: “);
// Register your service on port 5432
try {
s = new ServerSocket(5432);
} catch (IOException e) {
// ignore
}
// Run the listen/accept loop forever
while (true) {
try {
// Wait here and listen for a connection
Socket s1 = s.accept();
// Get output stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);

System.out.println();
System.out.println(“Write Something: “);
str=indata.readLine();
dos.writeUTF(str);

// Get an input stream from the socket
InputStream is = s1.getInputStream();

// Decorate it with a “data” input stream
DataInputStream dis = new DataInputStream(is);
// Read the input and print it to the screen
System.out.println(“Incoming From Client>>>:” +dis.readUTF());
//Display System Date
DateFormat defaultDate = DateFormat.getDateInstance();
System.out.println(defaultDate.format(new Date()));
//Display System Time
DateFormat shortTime = DateFormat.getTimeInstance(DateFormat.SHORT);
System.out.println(shortTime.format(new Date()));

// Close the connection, but not the server socket
dos.close();
s1.close();
dis.close();
} catch (IOException e) {
// ignore
}
}
}
}

SimpleClient Source Code

import java.net.*;
import java.io.*;
import java.util.*;
import java.text.DateFormat;
public class SimpleClient {
public static void main(String args[]) {

//Input From Keyboard
String str;
DataInputStream indata= new DataInputStream (System.in);

System.out.println(“Type in Something & Press Enter to Send it To The >>S E R V E R<<: “);

while(true){

try {

// Open your connection to a server, at port 5432

// localhost used here

Socket s1 = new Socket(“127.0.0.1″, 5432);

// Get an input stream from the socket

InputStream is = s1.getInputStream();

// Decorate it with a “data” input stream

DataInputStream dis = new DataInputStream(is);

// Read the input and print it to the screen

System.out.println(“Incoming From Server>>>:” +dis.readUTF());
//Display System Date
DateFormat defaultDate = DateFormat.getDateInstance();
System.out.println(defaultDate.format(new Date()));
//Display System Time
DateFormat shortTime = DateFormat.getTimeInstance(DateFormat.SHORT);
System.out.println(shortTime.format(new Date()));

// Get output stream associated with the socket
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
System.out.println();
System.out.println(“Write Something: “);
str = indata.readLine();
dos.writeUTF(str);

// When done, just close the steam and connection
dis.close();
dos.close();
s1.close();
} catch (ConnectException connExc) {
System.err.println(“Could not connect to the server.”);
} catch (IOException e) {
// ignore
}
}
}
}

Enjoy. Don’t forget to give me feedback. If you face any difficulties please let me know.

 

14 Responses

  1. Frank

    Hi,
    I want realize a dynamic website. It means, read permanently
    data via tcp socket by demand and show its result in form of
    values or animations. How to include an TCP socket client in
    my website? And how to send cyclic requests (my own protocol)
    and analize the results. I’m not expaert in Java – so it would
    very helpful to get a sample page.
    In VB6 runs fine. So it would be good that a sample page runs on
    a local webserver (xampp) and beside runs a VB-TCP server. Via
    webpage sending “Hello” and the server responds “world” and
    show this “world” on the page.
    Could you help me? – or give me any good idea or samples.
    Thanks a lot
    …waiting for your response.
    Frank

  2. Hi Frank. I’m not an expert in java either. You want to include TCP socket client in your website. Im afraid i haven’t have any experience about it. But I think it would be a lot more easier if you use PHP socket programming. This link might help:

    http://www.devshed.com/c/a/PHP/Socket-Programming-With-PHP/

    Thanks :)

  3. jojo

    Hello Robin, how are u?
    I want to ask you if you can make the Server keep sending messages without waiting for the Client and vise versa?

  4. Sribina Neyan

    I need a simple tutorial for learning java

  5. hi,, thanks for the code…
    but i still need teacher to practice..
    :D

  6. sharad

    hi ….. can u temme how to esatblish connection btw two clients using server ..

  7. Great entry, that everyone should see. Thanks for this entry..

  8. Great post, which everyone should be interested. Thanks for this entry..

  9. Very Nice website. I built mine and i was looking for some design ideas and you gave me a few. May i ask you whether you developed the website by youself?

    Thanks

  10. Redemptie

    Excellent tutorial, the thing thats gets me is there are so many streams, buffered streams, scanner streams, datainput streams. Do you have any tips on what to use and when to use certain kinds of streams. like the readline() in datainput Stream is deprecated, whilst id is not in the bufferedd stream. so many ways to do things in java, sometimes this can be confusing.

  11. Khaled

    thanks that helped me understand how to operate both cleint and server on the same IDE

  12. Reza

    Excellent Topics to learn, great.

  13. raj

    great thanks for ur info

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© mythrobin•com
credit