Category: Networking

In this tutorial I have shared simple client server program example to explain java socket programming. In this example I will use Socket and ServerSocket classes for connection oriented socket programming. Since data is shared between server and client over network in the form of streams so DataInputStream and DataOutputStream classes are used. Java Socket Programming (Client Server Program) Server

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

importjava.io.DataInputStream;

importjava.net.ServerSocket;

importjava.net.Socket;

classserver{

publicstaticvoidmain(Stringargs[]){

try{

//create socket, 5000 is port number

ServerSocket serverSocket=newServerSocket(5000);

System.out.println("Waiting for Client...");

//establish connection

Socket socket=serverSocket.accept();

System.out.println("Client Connected...");

//fetch incoming message

DataInputStream dis=newDataInputStream(socket.getInputStream());

Stringmessage=(String)dis.readUTF();

System.out.println("Client message: "+message);

//close connection

serverSocket.close();

}catch(Exceptione){

e.printStackTrace();

}

}

}

Above code is used to create server which is running on localhost on port number 5000. Client

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

importjava.io.DataOutputStream;

importjava.net.Socket;

importjava.util.Scanner;

classclient{

publicstaticvoidmain(Stringargs[]){

Stringmessage;

Scanner sc=newScanner(System.in);

try{

//localhost because server is running on local machine, otherwise use ip of server