I tried to make a simple java class that runs a server on localhost and just makes a page with the word test as an HTML title and the word test in the body. For some reason, when I run it and try to connect, it refuses to connect. Here's my code:
package Server.core;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerListenerThread extends Thread{
private int port;
private ServerSocket serverSocket;
public ServerListenerThread(int port) throws IOException {
this.port = port;
this.serverSocket = new ServerSocket(port);
}
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
String html = "<html><head><title>Test</title></head><body><h1>test</h1></body></html>";
final String CRLF = "\r\n"; // 13, 10
String response = "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + html.getBytes().length + CRLF + CRLF + html+ CRLF + CRLF;
outputStream.write(response.getBytes());
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
} catch(Exception e) {
}
}
}
In my main method, I start a new ServerListenerThread on port 276.
you need to keep your thread alive. you can use while for that.
below is the basic modification i did. you can refactor more.
Also create ServerSocket once only.
public class ServerListenerThread extends Thread{
public static void main(String args[]) throws IOException {
ServerListenerThread s1= new ServerListenerThread(276);
s1.start();
}
private int port;
private ServerSocket serverSocket;
public ServerListenerThread(int port) throws IOException {
this.port = port;
this.serverSocket = new ServerSocket(port);
}
#Override
public void run() {
while (true) {
// spin forever
try {
// ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
String html = "<html><head><title>Test</title></head><body><h1>test</h1></body></html>";
final String CRLF = "\r\n"; // 13, 10
String response =
"HTTP/1.1 200 OK" + CRLF + "Content-Length: " + html.getBytes().length + CRLF + CRLF + html
+ CRLF + CRLF;
outputStream.write(response.getBytes());
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
}
}
}
}
Related
I've created a client, a server and an object called CcyData. When the client connects to the server I would like the server the send a "Welcome message" like "Hello, you are client# " + clientNumber. as a String and then send an object CcyData. I've managed to get the sending of the CcyData object to work but when I try to read in the "Welcome message" with
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Welcome message from server: "+ input.readLine());
the client stops working, nothing happens. No error message. Below is my code. How can I solve this?
Server.
package net.something;
import java.io.IOException;
import java.net.ServerSocket;
public class SocketServer {
private ServerSocket serverSocket = null;
private int clientNumber = 0;
public SocketServer() {
}
public void listenSocket () {
int clientNumber = 0;
try{
serverSocket = new ServerSocket(9090);
System.out.println("Server started on port 9090");
} catch(IOException e) {
e.printStackTrace();
}
while (true) {
ClientSocket clientSocket;
try{
clientSocket = new ClientSocket(serverSocket.accept(), serverSocket, clientNumber++);
Thread thread = new Thread(clientSocket);
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Class ClientSocket
package net.something;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ClientSocket implements Runnable {
private Socket clientSocket;
private ServerSocket serverSocket;
private int clientNumber;
public ClientSocket(Socket clientSocket, ServerSocket serverSocket, int clientNumber) {
this.clientSocket = clientSocket;
this.serverSocket = serverSocket;
this.clientNumber = clientNumber;
System.out.println("New connection with client# " + clientNumber + " at " + clientSocket);
}
public void run() {
PrintWriter out;
ObjectOutputStream outObjectStream;
try {
out = new PrintWriter(clientSocket.getOutputStream());
out.println("Hello, you are client# " + clientNumber);
outObjectStream = new ObjectOutputStream(clientSocket.getOutputStream());
CcyData ccyData = new CcyData("EUR", 9.56);
System.out.println("CcyData: " + ccyData.getCcy() + " " + ccyData.getFxRate());
outObjectStream.writeObject(ccyData);
} catch (IOException e) {
e.printStackTrace();
}
}
public void finalize() {
try{
serverSocket.close();
System.out.println("Server socket closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
package net.something;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
public class SocketClient {
private Socket socket = null;
private BufferedReader input;
private ObjectInputStream inObjectStream = null;
public SocketClient() {
}
public void connectToServer() {
try{
socket = new Socket("127.0.0.1", 9090);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Welcome message from server: "+ input.readLine());
inObjectStream = new ObjectInputStream(socket.getInputStream());
CcyData ccyData = (CcyData) inObjectStream.readObject();
System.out.println(ccyData.getCcy() + " " + ccyData.getFxRate());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
finalize is only called when the JVM garbage collector decides that there are no more references to your thread and disposes it. Thus, you cannot ensure that finalize will be called when your thread has reached the end of its run() method. Try closing the socket in the run method instead!
I want to write a socket client to send a request to a server and get response back. It works, but not right.
Here is my code:
public String send(final String data) {
Socket client = null;
String response = null;
try {
client = new Socket(this.host, this.port);
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(data);
final InputStream inFromServer = client.getInputStream();
final DataInputStream in = new DataInputStream(inFromServer);
response = in.readUTF();
} catch (final IOException e) {
this.log.error(e);
this.log.error("Sending message to server " + this.host + ":" + this.port + " fail", e);
} finally {
if (client != null) {
try {
client.close();
} catch (final IOException e) {
this.log.error("Can't close socket connection to " + this.host + ":" + this.port, e);
}
}
}
if (StringUtils.isBlank(response)) return null;
return response;
}
The problem is: I didn't got the full response with in.readUTF(). I always got a response with the same length as the sent data's length (variable data). I have tested with other GUI client and got the full response. So it's not a problem of the server.
Does someone known, what i did wrong?
UPDATE
Thanks EJP and Andrey Lebedenko. I think, my problems are the functions writeUTF and readUTF. So i have edited my code in the try block so:
Charset charset = Charset.forName("ISO-8859-1");
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.write(data.getBytes(charset));
final InputStream inFromServer = client.getInputStream();
final BufferedReader in = new BufferedReader(new InputStreamReader(inFromServer, charset));
response = in.readLine();
And it worked now.
If it works with Telnet, as per your comment, the server isn't using readUTF(), so your writeUTF() is already wrong, and the server is therefore unlikely to be using writeUTF() either, which would make your readUTF() wrong as well. You can't use these methods arbitrarily: they can only interchange data between themselves.
I'll bet your GUI client that works doesn't use them either.
Without knowing what does server part do, it is kind of difficult (if possible at all) to trace down the root cause. So in the most honest hope that it will help I just share this code with which I've tested the fragment above.
package tcpsendreceive;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SendReceive {
private static final Logger log = Logger.getLogger(SendReceive.class.toString());
private final String host;
private final int port;
private Server server;
class Server extends Thread
{
private final ServerSocket serverSocket;
public Server(ServerSocket s)
{
serverSocket = s;
}
#Override
public void run()
{
Socket connection;
SendReceive.this.log.log(Level.INFO, "Server: DoubleEcho Server running on "+this.serverSocket.getLocalPort());
try{
do {
connection = this.serverSocket.accept();
SendReceive.this.log.log(Level.INFO, "Server: new connection from "+connection.getRemoteSocketAddress());
int b;
do {
DataInputStream in = new DataInputStream(connection.getInputStream());
String s = in.readUTF();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeUTF(s+","+s); // echo it back TWICE
out.flush();
connection.shutdownOutput();
connection.close();
} while(!connection.isClosed());
}
while(true);
}
catch(IOException ioe)
{
SendReceive.this.log.log(Level.SEVERE, "IOException in server! - STOP", ioe);
}
finally {
try{
this.serverSocket.close();
} catch (Exception e) {
SendReceive.this.log.log(Level.SEVERE, "IOException closing server! - FATAL", e);
}
try{
if(!connection.isClosed())
connection.close();
} catch (Exception e) {
SendReceive.this.log.log(Level.SEVERE, "IOException closing server! - FATAL", e);
}
}
}
}
public SendReceive(String host, int port)
{
this.host = host;
this.port = port;
try{
this.server = new Server(new ServerSocket(this.port));
this.server.start();
}
catch(IOException ioe)
{
this.log.log(Level.SEVERE, "IOException while creating server! - STOP", ioe);
}
}
public String send(final String data) {
Socket client = null;
String response = null;
try {
client = new Socket(this.host, this.port);
final OutputStream outToServer = client.getOutputStream();
final DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(data);
final InputStream inFromServer = client.getInputStream();
final DataInputStream in = new DataInputStream(inFromServer);
response = in.readUTF();
} catch (final IOException e) {
this.log.log(Level.SEVERE, "Sending message to server " + this.host + ":" + this.port + " fail", e);
} finally {
if (client != null) {
try {
client.close();
} catch (final IOException e) {
this.log.log(Level.SEVERE, "Can't close socket connection to " + this.host + ":" + this.port, e);
}
}
}
if(response == null || response.isEmpty())
return null;
return response;
}
}
Test-demo
package tcpsendreceive;
public class Main {
public static void main(String[] args)
{
String data = "AAABBB";
SendReceive sr = new SendReceive("localhost", 5000);
String res = sr.send(data);
System.out.println("Sent: "+data);
System.out.println("Received: "+res);
}
}
Result (key part):
Sent: AAABBB
Received: AAABBB,AAABBB
Hope it helps.
EDIT
1. Corrected wrapper flush instead of socket stream flush. Still believe it is good practice to flush the stream wrapper before closing the socket.
Client socket closed in IOException block (since they aren't automatically closed on ServerSocket shutdown). Thanks #EJP
P.s. I should admit I was bit surprised by such an attention to the humble test server code, especially compared to other dirty tests we all have seen on SO. Flattered. :)
I have a problem which i've already been struggling for 3 days. I need to create server based on socket connection beetween the different local networks.
I found a lot of examples like this :
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* Created by yar 09.09.2009
*/
public class HttpServer {
public static void main(String[] args) throws Throwable {
ServerSocket ss = new ServerSocket(9999);
while (true) {
Socket s = ss.accept();
System.err.println("Client accepted");
new Thread(new SocketProcessor(s)).start();
}
}
private static class SocketProcessor implements Runnable {
private Socket s;
private InputStream is;
private OutputStream os;
private SocketProcessor(Socket s) throws Throwable {
this.s = s;
this.is = s.getInputStream();
this.os = s.getOutputStream();
}
public void run() {
try {
readInputHeaders();
writeResponse("<html><body><h1>Hello from Habrahabr</h1></body></html>");
} catch (Throwable t) {
/*do nothing*/
} finally {
try {
s.close();
} catch (Throwable t) {
/*do nothing*/
}
}
System.err.println("Client processing finished");
}
private void writeResponse(String s) throws Throwable {
String response = "HTTP/1.1 200 OK\r\n" +
"Server: YarServer/2009-09-09\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: " + s.length() + "\r\n" +
"Connection: close\r\n\r\n";
String result = response + s;
os.write(result.getBytes());
os.flush();
}
private void readInputHeaders() throws Throwable {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while(true) {
String s = br.readLine();
if(s == null || s.trim().length() == 0) {
break;
}
}
}
}
}
But problem is :
i can access to this ip:port only from the same local network. If i trying to connect from the same network (from Android smartphone to local computer which has the same network ip)? so in this case all is successful, but if i trying to run the same Server sample code on, say for example AWS (Amazon Web Server)
it doesn't work :(
-> Couldn't get I/O for the connection to 172.31.23.98 (java)
or
-> org.apache.http.conn.ConnectTimeoutException: Connect to 172.31.23.98:9999 timed out (groovy)
i'm using this sample code of Server :
public static void main(String[] args) throws IOException {
int portNumber = 9998;
BufferedOutputStream bos = null;
while (true) {
try (ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
InputStream in = clientSocket.getInputStream();
BufferedReader inWrapper = new BufferedReader(new InputStreamReader(in))) {
FileOutputStream fos = new FileOutputStream(new File("D:/BufferedAudio.wav"));
bos = new BufferedOutputStream(fos);
System.out.println("Connected with client");
String inputLine, outputLine;
int bytesRead;
byte[] buffer = new byte[1024 * 1024];
while ((bytesRead = in.read(buffer)) > 0) {
bos.write(buffer, 0, bytesRead);
System.out.println(new String(buffer, Charset.defaultCharset()));
bos.flush();
out.println("Hello!!! I'm server");
}
bos.close();
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
throw e;
}
System.out.println("Upps, the loop was unexpectedly out");
}
}
Here's the code of client :
public static void main(String[] args) throws IOException {
String IP = "172.31.23.98";
int port = 9998;
try (
Socket connectionSocket = new Socket(IP, port);
PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()))
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + IP);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
IP);
System.exit(1);
}
}
These are the samples from the internet.
Amm how can i modify this code to access from Client to Server from different networks ?
The IP range 172.16.0.0 to 172.31.255.255 is a private address space for use in local area networks. IPs from that range are only valid in the same private LAN.
When you deploy your server software on a host on the Internet which is outside of your local area network, you need to replace it with the IP address of that host. I never used AWS, but the first place I would be looking for when I would want to know the public IP address of a server I rent, would be the web-based control panel. When you have shell access to the server, you can also find it out with ipconfig on Windows and ifconfig on Unix.
I'm trying to run a client-server program in java on Netbeans.
Here's the code for the server:
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]); #line 48, error arises here.
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Here's the code for the client:
// File Name GreetingClient.java
import java.io.*;
import java.net.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0]; #line 10, error arises here
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
So when I want to simulate the client and the server running together I first run the server.
Once the server is running I need to run the client.
However when I try to run the server file, I get the following error:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingServer.main(GreetingServer.java:48)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Similarly, when I try to run the client program, I get the following error:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingClient.main(GreetingClient.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Why is this happening? Please help.
UPDATE:
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
// File Name GreetingClient.java
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
There is no error on the server side now. But I am still getting the following error on the client side:
run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GreetingClient.main(GreetingClient.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Your code supposes that you pass the port you want to use as an argument so :
Either you run your application with the line Patryk RoszczyniaĆa posted
If you don't want to use it, just delete the lines :
String serverName = args[0];
int port = Integer.parseInt(args[0]);
and replace them by hardcoded values like :
String serverName = "MyServerName";
int port = 3000;
Update :
I just tested your code, in fact, the serverName is the address you use to connect to the server, so replace it by "localhost" if you are running both client and server on the same machine.
Tested code :
Here is the updated code I tested and it should work perfectly if you run both on the same machine.
Client :
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "localhost";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
Server :
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(20000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
To run SocketServer you need to pass port on which server will work. For example:
SocketServer server = new SocketServer(1234);
The problem is that you want to pass port by java argument and you aren't doing that. First of all before use of any variable you should first validate it.
if (args.length>0) {
int port = Integer.parseInt(args[0]); #line 48, error arises here.
}
Your program requires params but I think that you probably run your program without params.
You should run program in this way: java -jar app.jar 1234
But you do it in this way: java -jar app.jar
In this article you will find how to pass parameters to java program using netbeans http://netbeanside61.blogspot.com/2009/02/using-command-line-arguments-in.html.
If you are new in java you should first read this tutorial http://docs.oracle.com/javase/tutorial/networking/sockets/. It's very helpful.
Is there a way I could create an array of network streams in java. C# supports creation of an array of Network Streams.
AFAIK we need to create separate InputStreams and OutputStreams in order to receive and send data in Java.
What I want to do is to make a number of TCP connections to send and receive data.
Is there a work around in java for this?
You can achieve that by creating multiple instances of Socket as follows:
Server.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private static int CLIENT_COUNT = 0;
public static void main(String[] args) throws IOException
{
ServerSocket ss = new ServerSocket(2000);
while(true)
{
Socket s = ss.accept();
new SocketHandler("Handler#" + ++CLIENT_COUNT, s).start();
}
}
}
class SocketHandler extends Thread
{
private PrintWriter pw;
private BufferedReader br;
public SocketHandler(String name, Socket socket) throws IOException
{
super(name);
this.pw = new PrintWriter(socket.getOutputStream(), true);
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run()
{
String message;
try
{
while((message = br.readLine()) != null)
{
System.out.println("Server#" + getName() + " - Client sent: " + message);
sendMessage("Server#" + getName() + ": echo " + message);
}
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Server#" + getName() + " -> IOException");
}
}
public void sendMessage(String message)
{
pw.println(message);
System.out.println("Server#" + getName() + " is sending ~ " + message);
}
}
Client.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
private static int SOCKET_COUNT = 0;
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket s1 = new Socket(InetAddress.getLocalHost(), 2000);
Socket s2 = new Socket(InetAddress.getLocalHost(), 2000);
Socket s3 = new Socket(InetAddress.getLocalHost(), 2000);
Socket s4 = new Socket(InetAddress.getLocalHost(), 2000);
LocalSocketHandler h1 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s1);
LocalSocketHandler h2 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s2);
LocalSocketHandler h3 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s3);
LocalSocketHandler h4 = new LocalSocketHandler("LocalHandler#" + ++SOCKET_COUNT, s4);
h1.start();
h2.start();
h3.start();
h4.start();
h1.sendMessage("I am socket #1!");
h2.sendMessage("I am socket #2!");
h3.sendMessage("I am socket #3!");
h4.sendMessage("I am socket #4!");
}
}
class LocalSocketHandler extends Thread
{
private PrintWriter pw;
private BufferedReader br;
public LocalSocketHandler(String name, Socket socket) throws IOException
{
super(name);
this.pw = new PrintWriter(socket.getOutputStream(), true);
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
#Override
public void run()
{
String message;
try
{
while((message = br.readLine()) != null)
{
System.out.println("Client#" + getName() + " - Server sent: " + message);
}
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Client#" + getName() + " -> IOException");
}
}
public void sendMessage(String message)
{
pw.println(message);
System.out.println("Client#" + getName() + " is sending ~ " + message);
}
}
Client's console:
Client#LocalHandler#1 is sending ~ I am socket #1!
Client#LocalHandler#2 is sending ~ I am socket #2!
Client#LocalHandler#3 is sending ~ I am socket #3!
Client#LocalHandler#4 is sending ~ I am socket #4!
Client#LocalHandler#1 - Server sent: Server#Handler#1: echo I am socket #1!
Client#LocalHandler#3 - Server sent: Server#Handler#3: echo I am socket #3!
Client#LocalHandler#2 - Server sent: Server#Handler#2: echo I am socket #2!
Client#LocalHandler#4 - Server sent: Server#Handler#4: echo I am socket #4!
Server's console:
Server#Handler#1 - Client sent: I am socket #1!
Server#Handler#1 is sending ~ Server#Handler#1: echo I am socket #1!
Server#Handler#3 - Client sent: I am socket #3!
Server#Handler#3 is sending ~ Server#Handler#3: echo I am socket #3!
Server#Handler#2 - Client sent: I am socket #2!
Server#Handler#2 is sending ~ Server#Handler#2: echo I am socket #2!
Server#Handler#4 - Client sent: I am socket #4!
Server#Handler#4 is sending ~ Server#Handler#4: echo I am socket #4!