Kodejava website provides Java examples to use the Java API (Application Programming Interface) to build Java applications. In this website you will find a lot of examples grouped by the Java API packages or libraries.

How do I create a client-server socket communication?

In this example you’ll see how to create a client-server socket communication. The example below consist of two main classes, the ServerSocketExample and the ClientSocketExample. The server application listen to port 7777 at the localhost. When we send a message from the client application the server receive the message and send a reply to the client application.

The communication in this example using the TCP socket, it means that there is a fixed connection line between the client application and the server application.

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

packageorg.kodejava.example.net;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.lang.ClassNotFoundException;

import java.lang.Runnable;

import java.lang.Thread;

import java.net.ServerSocket;

import java.net.Socket;

publicclassServerSocketExample{

privateServerSocket server;

privateintport=7777;

publicServerSocketExample(){

try{

server=newServerSocket(port);

}catch(IOExceptione){

e.printStackTrace();

}

}

publicstaticvoidmain(String[]args){

ServerSocketExample example=newServerSocketExample();

example.handleConnection();

}

publicvoidhandleConnection(){

System.out.println("Waiting for client message...");

//

// The server do a loop here to accept all connection initiated by the