Tuesday, August 5, 2008

A Simple TCP program for Beginners

This is a simple TCP program in which the server sends the data and the client receives it and keeps on displaying it untill the server sends a value -1. This code is too simple to explain.

MyServer.java


import java.net.*;
import java.io.*;
public class MyServer
{
public static void main(String xx[]) throws IOException
{
ServerSocket ss=new ServerSocket(5439);
Socket s=ss.accept();
byte arr[]=new byte[256];
String str=new String();
str="welcome";
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(read);
while(!str.equals("-1"))
{
str=br.readLine();
arr=str.getBytes();
OutputStream out=s.getOutputStream();
out.write(arr);
}
ss.close();
}
}






MyClient.java


import java.net.*;
import java.io.*;
public class MyClient
{
public static void main(String xx[]) throws IOException
{
Socket client=new Socket(InetAddress.getLocalHost(),5439);
byte bb[]=new byte[256];
InputStream in=client.getInputStream();
in.read(bb);
String obj=new String(bb);
while(!obj.equals("-1"))
{
System.out.println(obj);
bb=new byte[256];
in.read(bb);
obj=new String(bb);
}
client.close();

}
}