954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Simple Client Server Instant Messaging Java code using UDP datagrams

Hi,

I am trying to write a java program for a client server instant messaging system using UPD datagram. I am trying to think of how to start. Anyone has any suggestions? Please advise

woolf
Newbie Poster
1 post since Sep 2005
Reputation Points: 10
Solved Threads: 0
 

Hi !!! I built a program for msg transfer in java using udp.

//udp server
import java.net.*;
import java.io.*;
class Server
{
public static void main(String args[])throws IOException
{
byte b[]=new byte[1024];
DatagramSocket ds=new DatagramSocket(5001);
DatagramPacket dp=new DatagramPacket(b,1024);

//System.out.println("receiving");
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
//receive file name
System.out.println("Received file "+str);
FileReader fr=new FileReader(str);
BufferedReader br1=new BufferedReader(fr);
while((str=br1.readLine())!=NULL)
{
b=str.getBytes();
ds.send(new DatagramPacket(b,b.length,InetAddreass.getLocalHost(),5000));
}
ds.close();
}
}

//udp client

import java.net.*;
import java.io.*;
class Client
{
public static void main(String args[])throws IOException
{
byte b[]=new byte[1024];
DatagramSocket ds=new DatagramSocket(5000);
DatagramPacket dp=new DatagramPacket(b,1024);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter file name\n");
String str1;
str1=dis.readLine();
b=str1.getBytes();
ds.send(new DatagramPacket(b,b.length,InetAddress.getLocalHost(),5001));
System.out.println("Contents of file:"+str1+"\n");
while(str1!=NULL)
{
ds.receive(dp);
str1=new String(dp.getData(),0,dp.getLength());//receive file contents
System.out.println(str1);
}
ds.close();
}
}

ashu_305
Newbie Poster
3 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

@ashu_305 congratulation on your program, just shame you are about 4 year too late...

PS: Next step in your messaging service would be perhaps some GUI and use of threads. Good luck

peter_budo
Code tags enforcer
Moderator
15,436 posts since Dec 2004
Reputation Points: 2,806
Solved Threads: 902
 

How to establish the connection between two hosts through socket programming(TCP) in java.

vani.golakoti
Newbie Poster
4 posts since May 2010
Reputation Points: 10
Solved Threads: 0
 

hi

Iwant simple code chat in java

zahertal
Newbie Poster
1 post since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You