Friday, September 5, 2008 | |

Simplest network Program in Java

Before going to a GUI network program, I decided to write a simple network program in Java. Wrote it and code is given below. A network program in Java can not be simpler than this. basically this program has two files.
  • s.java
  • c.java
s and c stands for server and client respectively. client sends a piece of text "This is the simplest text" to server. Server displays it. Thats all. Simple Huh!

s.java:


import java.net.*;
import java.io.*;

class s
{
ServerSocket servSoc=null;
DataInputStream din = null;
String s;
Socket soc;

s()
{
try{
servSoc=new ServerSocket(2008);
soc=servSoc.accept();
din=new DataInputStream(soc.getInputStream());

while(true)
{
s=din.readLine();
System.out.println(s);

}
}
catch(Exception e){}
}
public static void main(String ars[])
{
s s1=new s();

}
}



c.java:


import java.net.*;
import java.io.*;

class c
{
Socket soc = null;
PrintWriter pr=null;

c()
{
try{
soc=new Socket("localhost",2008);
pr=new PrintWriter(soc.getOutputStream(),true);
pr.println("This is the simplest text");
}
catch(Exception e)
{}

}
public static void main(String args[])
{
c c1=new c();
}
}


0 comments: