CLIENT TO SERVER
- InputStream − The InputStream is used to read data from a source.
- OutputStream − The OutputStream is used for writing data to a destination.
Read More
WEBSITE - 1
WEBSITE - 2
WEBSITE - 3
MyClient.java
// importing java packages
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String args[]) {
try
{
// create a new socket for
communicating with the server
Socket skt = new
Socket("127.0.0.1", 6999);
System.out.println("Connected to
server");
// declaring a message
String msg = "Hello Server";
//creating output stream for socket(skt)
OutputStream os =
skt.getOutputStream();
//creating object for output stream
ObjectOutputStream oos = new
ObjectOutputStream(os);
// send a message to server using writeobject
oos.writeObject(msg);
System.out.println("Sent a
message to server");
// close object output stream
oos.close();
// close output stream
os.close();
// close socket
skt.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
MyServer.java
//import packages
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
// Create a new server socket that
listens at port 6999
ServerSocket ss = new
ServerSocket(6999);
System.out.println("Server is
lisenting ... ");
//wait for connection from client
on port 6999
Socket skt = ss.accept();
//InputStream for getting input from client
InputStream is = skt.getInputStream();
//declare Object for InputStream
ObjectInputStream ois = new
ObjectInputStream(is);
// recieve message from client
String msg = (String)ois.readObject();
// display the output
System.out.println("Server
recieved message : " + msg);
System.out.println("Server is
exiting ... ");
/* close open streams and socket
*/
ois.close();
is.close();
skt.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
1. First run MyServer.java
2. Second run MyClient.java
SOURCE CODE:
1. CLIENT
2. SERVER
OUTPUT
MyServer.java
MyClient.java
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.