- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to make a socket displaying message to a single client in Java
Problem Description
How to make a socket displaying message to a single client?
Solution
Following example demonstrates how to make a socket displaying message to a single client with the help of ssock.accept() method of Socket class.
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class BeerServer {
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
Socket sock = ssock.accept();
ssock.close();
PrintStream ps = new PrintStream(sock.getOutputStream());
for (int i = 10; i >= 0; i--) {
ps.println(i + " from Java Source and Support.");
}
ps.close();
sock.close();
}
}
Result
The above code sample will produce the following result.
Listening 10 from Java Source and Support 9 from Java Source and Support 8 from Java Source and Support 7 from Java Source and Support 6 from Java Source and Support 5 from Java Source and Support 4 from Java Source and Support 3 from Java Source and Support 2 from Java Source and Support 1 from Java Source and Support 0 from Java Source and Support
java_networking.htm
Advertisements