by
354 16
2
6
2,570
1
Top 1% !
Popular
Famous
Tagged
Specified
OpenSource
Popularity: 6630th place

Published on:

LanguageJava
LicenseMIT_X11

Client socket in Java

This code shows a simple socket client in java.
The client will connect to the socket server and get the date string.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/33142/Client-socket-in-Java?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import javax.swing.JOptionPane; /** * Trivial client for the date server. */ public class DateClient { /** * Runs the client as an application. First it displays a dialog * box asking for the IP address or hostname of a host running * the date server, then connects to it and displays the date that * it serves. */ public static void main(String[] args) throws IOException { String serverAddress = JOptionPane.showInputDialog( "Enter IP Address of a machine that is\n" + "running the date service on port 9090:"); Socket s = new Socket(serverAddress, 9090); String hostAddress = s.getInetAddress().getHostAddress(); String hostName = s.getInetAddress().getHostName(); BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); StringBuilder sb = new StringBuilder(); sb.append(input.readLine()); s.close(); sb.append('\n'); sb.append(hostAddress); sb.append('\n'); sb.append(hostName); sb.append('\n'); JOptionPane.showMessageDialog(null, sb.toString()); System.exit(0); } }

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus