Creating a Server
We can write a socket that can be used to connect a server and a client. Once the socket is created, the server can send data to the client and the client can receive it. All we have to do is to just send the data from the server to the socket. The socket will take care of whom to send the data on the network. Let us follow these steps to create a server that sends some strings (messages) to the client.
- At server side, create a server socket with some port number. This is done using ServerSocket class as:
- Now, we should make the server wait till a client accepts connection. This is done using accept() method.
- Attach output string to the server socket using getOutputStream() method. This method returns OutputStream object. This stream is used by the socket to send data to client.
- Take another stream like PrintStream to send data till the socket.
- Finally the PrintStream is used by the server to send data to the client. To send data we have print() or println() methods available in PrintStream.
- Then close the connection. This can be done by closing all the streams and sockets at server side as:
ss.close(); // close ServerSocket
p.close(); // close Socket
ps.close(); // close PrintStream Program:
//Write a program to create a server to send some strings(message) to the client.
public static void main(String args)throws Exception
// Create a server socket with some socket number
// let the ServerSocket wait till a client accepts connection
// attach Output Stream to the server socket
// attach print stream to send data to the socket
// send 2 strings to the client
String str=”Hello client”;
// close connection by closing the streams and sockets
D:\my java>javac Alok.java
DO NOT RUN THIS PROGRAM TILL THE CLIENT IS ALSO CREATED...
Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects
SILAN Technology, BBSR Call to: 0674-2361252