File tree Expand file tree Collapse file tree
core-java-modules/core-java-networking-3/src/main/java/com/baeldung/timeout Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .timeout ;
2+
3+ import java .io .BufferedReader ;
4+ import java .io .IOException ;
5+ import java .io .InputStreamReader ;
6+ import java .io .PrintStream ;
7+ import java .net .Socket ;
8+ import java .net .UnknownHostException ;
9+
10+ public class TcpClientSocket {
11+
12+ private Socket socket ;
13+ private PrintStream out ;
14+ private BufferedReader in ;
15+
16+ public void connect (String host , int port ) {
17+ try {
18+ socket = new Socket (host , port );
19+ socket .setSoTimeout (30000 );
20+ System .out .println ("connected to " + host + " on port " + port );
21+
22+ out = new PrintStream (socket .getOutputStream (), true );
23+ System .out .println ("Sending message ... " );
24+ out .println ("Hello world" );
25+
26+ in = new BufferedReader (new InputStreamReader (socket .getInputStream ()));
27+ out .println (in .readLine ());
28+
29+ System .out .println ("Closing connection !!! " );
30+ in .close ();
31+ out .close ();
32+ socket .close ();
33+
34+ } catch (UnknownHostException e ) {
35+ System .err .println (e );
36+ } catch (IOException e ) {
37+ System .err .println (e );
38+ }
39+ }
40+
41+ public static void main (String [] args ) throws IOException {
42+ TcpClientSocket client = new TcpClientSocket ();
43+ client .connect ("127.0.0.1" , 5000 );
44+ }
45+
46+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .timeout ;
2+
3+ import java .io .BufferedReader ;
4+ import java .io .IOException ;
5+ import java .io .InputStreamReader ;
6+ import java .net .ServerSocket ;
7+ import java .net .Socket ;
8+
9+ public class TcpServerSocket {
10+
11+ private Socket socket ;
12+ private ServerSocket serverSocket ;
13+ private BufferedReader in ;
14+
15+ public TcpServerSocket (int port ) {
16+
17+ try {
18+ serverSocket = new ServerSocket (port );
19+ System .out .println ("Server is listening on port :: " + port );
20+ System .out .println ("Waiting for a client ..." );
21+
22+ socket = serverSocket .accept ();
23+ socket .setSoTimeout (40000 );
24+ System .out .println ("Client connected !! " );
25+
26+ in = new BufferedReader (new InputStreamReader (socket .getInputStream ()));
27+
28+ String line = in .readLine ();
29+ System .out .println (line );
30+
31+ System .out .println ("Closing connection !!! " );
32+
33+ socket .close ();
34+ in .close ();
35+ } catch (IOException i ) {
36+ System .out .println (i );
37+ }
38+ }
39+
40+ public static void main (String args []) {
41+ TcpServerSocket server = new TcpServerSocket (5000 );
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments