Monday 16 September 2019

Socket Programming in java

                                    Creating Chat Server in Java 

1. Open two notepad files.
2. Write the codes of Server and Client in separate files.

a.) Server Code
import java.io.*;
import java.net.*;
public class MyServerCode
{DataInputStream dIS;
public MyServerCode()
{
try
{
System.out.println("Server has Started\n Waiting for Client Connection Request...");
ServerSocket ss=new ServerSocket(1234);
Socket s=ss.accept();//Waiting for client connection
System.out.println("CLIENT has  Connected");
dIS=new DataInputStream(s.getInputStream());
serverChat();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
catch(Exception e)
{
System.out.println(e);
}
}
public void serverChat() throws IOException
{
String str;
do
{
str=dIS.readUTF();
System.out.println("CLIENT Message ::"+str);
}
while(!str.equals("stop"));
}
public static void main(String args[])
{
new MyServerCode();
}
}
b.) Client-Side Coding

import java.net.*;
import java.io.*;
public class MyClientCode
{DataOutputStream dOut;
public MyClientCode()
{
try
{
Socket s=new Socket("localhost",1234);
dOut= new DataOutputStream(s.getOutputStream());
System.out.println("Enter the data to send to the SERVER");
clientChat();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
catch(Exception e)
{
System.out.println(e);
}
}
public void clientChat() throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String st;
do
{
st=br.readLine();
dOut.writeUTF(st);
dOut.flush();
}
while(!st.equals("stop"));
}
public static void main(String args[])
{
new MyClientCode();
}
}

3. Now Compile the codes on different Command Prompts.
a.) Firstly compile the Server Code like this:


Now server is waiting for a client to connect.

b.) Compile and run client-side code.




Enter the message you want to send to the server 


Now the server will read the message will print it.




No comments:

Post a Comment

DBMS NOTES UNIT 3

                                                              UNIT 3  ER (Entity Relationship) An entity-relationship model is known as an E...