There are many tutorials where explains about socket server/client sides, but all them are very trivial. Is there any tutorial for production ready code? I'm new in sockets. There is a client, that sends strings to server. I must create the server side. in server side I read string from client and after some manipulation saves them in db. I must response to client only IF I get string like "Error" for example. and if there are no any daya from client in 30 secs, I must close client connection, but server side must works. this is my test Client side:
public class ClientSideSocket2 {
public static void main(String[] args) {
String serverName = "localhost";
int port = 5555;
String line = "";
Socket client = null;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
PrintWriter toServer = new PrintWriter(client.getOutputStream(), true);
BufferedReader fromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
List<String> messages = new ArrayList<>();
for (int i = 0; i < 6; i++) {
messages.add("Message " + i+1);
}
messages.add("abc");
for (int i = 0; i < messages.size(); i++) {
toServer.println(messages.get(i));
if ((line = fromServer.readLine()) != null) {
System.out.println("Responce from server: " + line);
}
}
toServer.close();
fromServer.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
and my server side:
public class TRSServerInterface implements Runnable {
private ServerSocket serverSocket = null;
private Socket socket = null;
boolean runner = true;
String message = "";
public TRSServerInterface() {}
#Override
public void run() { // default run method of Thread class and Runnable interface
try {
int serverPort = 5555;
ServerSocket serverSocket = new ServerSocket(serverPort);
while(true) {
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connected to " + socket.getRemoteSocketAddress());
//get the input and output streams
PrintWriter toClient = new PrintWriter(socket.getOutputStream(), true);
BufferedReader fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
do {
message = fromClient.readLine();
System.out.println("From client > " + message);
if (message.equals("abc")) {
toClient.println("Message from server");
}
else {
toClient.println("");
}
} while (!message.equals(""));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// try {
// objectOut.close();
// objectIn.close();
// socket.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
}
is my solution corrent and how I can close connection with client if there are no any data in 30 secs.
There are several production ready frameworks that should be used instead of rolling your own. Socket timeouts can be used to control how long different operations are allowed to take before an exception is thrown.
Related
I'm creating two program files (one client one server).
Each file has one thread (one thread for server, one thread for client)
At runtime, there is supposed to be only one server, and there is supposed to be multiple and/or potentially infinite number of clients connecting to the server at the same time)
In order to get multiple clients to run, the user opens multiple command prompt / mac terminal windows (each window being one client) (one window being the server, so it requires at least two windows to run)
Once a client is connected, it can send messages (utf-8 strings) to the server. It will also receive from the server all messages sent from the other connected clients (it will not receive messages sent from itself).
The port number I am using to connect is 5344 (localhost).
Screenshot of client error:
Screenshot of server (no errors):
The error message is:
Exception in thread “Thread-75562” java.lang.NullPointerException at ChatClient$1.run(ChatClient.java:39)
The "39" is the line of code (I think) that the error is pointing at.
Screenshot of line 39 in ChatClient.java:
I have notice that some people use
Socket socket = new Socket(host, portNumber);
without calling any Socket.connect(host, portNumber); to connect to a server.
Does socket.connect() ever need to be used to connect a client to a server?
Code of ChatClient.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatClient
{
private static Socket Socket;
static int numberOfClients = 0;
public static void main(String args[])
{
//If I wanted to create multiple clients, would this code go here? OR should the new thread creation be outside the while(true) loop?
while (true)
{
String host = "localhost";
int numberOfClients = 0;
Thread ChatClient1 = new Thread ()
{
public void run()
{
try
{
//Client begins, gets port number, listens, connects, prints out messages from other clients
int port = 0;
int port_1number1 = 0;
int numberofmessages = 0;
String[] messagessentbyotherclients = null;
System.out.println("Try block begins..");
System.out.println("Chat client is running");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
if(args.length>0)
{
port = Integer.valueOf(port_number1);
}
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
try
{
Socket.connect(null);
}
catch (IOException e1)
{
e1.printStackTrace();
}
System.out.println("Client has connected to the server");
boolean KeepRunning = true;
while(KeepRunning)
{
for(int i = 0; i < numberOfClients; i++)
{
System.out.println(messagessentbyotherclients);
}
try
{
//client creates new message from standard input
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
}
catch (IOException e)
{
e.printStackTrace();
}
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input encoded in UTF-8 string format
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
input=null;
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
//Sending the message to server
String sendMessage = newmessage;
try
{
OutputStream os = Socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(sendMessage + "\n");
bw.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("Message sent to server: "+sendMessage);
}
}
finally
{
}
}
};
ChatClient1.start();
}
}
}
Code of ChatServer.java:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ChatServer
{
private static Socket socket;
public static void main(String args[])
{
Thread ChatServer1 = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
int port_number1 = 0;
int numberOfClients = 0;
boolean KeepRunning = true;
if(args.length>0)
{
port_number1 = Integer.valueOf(args[0]);
}
System.out.println("Waiting for connections on port " + port_number1);
try
{
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//create a list of clients
ArrayList<String> ListOfClients = new ArrayList<String>();
//connect to client
// socket = serverSocket.accept();
//add new client to the list, is this the right way to add a new client? or should it be in a for loop or something?
ListOfClients.add("new client");
numberOfClients += 1;
System.out.println("A client has connected. Waiting for message...");
ListOfClients.add("new client" + numberOfClients);
//reading encoded utf-8 message from client, decoding from utf-8 format
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
//relaying message to every other client besides the one it was from
for (int i = 0; i < ListOfClients.size(); i++)
{
if(ListOfClients.get(i)!="new client")
{
String newmessage = null;
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (socket != null)
{
socket.close ();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
ChatServer1.start();
}
}
My question is: How to resolve the error and/or should I delete the socket.connect() while somehow still being able to connect to the server as a client?
I tried to write a simple program that runs a server and then accepts two clients. Then one of them tries to send a string to another client.
but my code doesn't work and I don't know why.
This is my TestClient class:
public class TestClient extends Thread{
int id;
String Name;
Socket client;
boolean isAsk;
public TestClient(int id,String clientName,boolean isAsk) throws IOException {
this.id=id;
this.Name=clientName;
this.isAsk=isAsk;
}
public void connectTheClientToTheLocalHost(ServerSocket server){
try {
client = new Socket("localhost",1111);
server.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFromTerminal(){
try {
InputStream is=client.getInputStream();
OutputStream os = client.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("sdklfsdklfk");
pw.flush();
pw.close();
}catch (IOException e){
e.printStackTrace();
}
}
public void closeTheCientSocket(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(){
try {
Scanner sc = new Scanner(client.getInputStream());
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("file1.txt")));
String st =sc.nextLine();
bw.write(st);
bw.close();
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void run() {
if(isAsk){
readFromTerminal();
}
else{
write();
}
}
and this is the main function:
public class PCServer {
public static void main(String[] args){
try {
ServerSocket s = new ServerSocket(1111);
TestClient t1=(new TestClient(1,"reza",true));
TestClient t2=(new TestClient(2,"man",false));
t1.connectTheClientToTheLocalHost(s);
t1.start();
Scanner sc = new Scanner(t1.client.getInputStream());
String st=sc.nextLine();
System.out.println(st);
t1.closeTheCientSocket();
t2.connectTheClientToTheLocalHost(s);
PrintWriter pw = new PrintWriter(t2.client.getOutputStream());
pw.println(st);
pw.flush();
t2.start();
t2.closeTheCientSocket();
}catch (Exception e){
e.printStackTrace();
}
}
}
actually this code returns an exception in
String st=sc.nextLine();
in main function and says that there is no line found.
what is the problem?
ServerSocket in java usually used in another way.
If you need point-to-point connection, one host creates a ServerSocket and accepts connections. Examples:
First host example:
try(ServerSocket serverSocket = new ServerSocket(5555);
Socket socket = serverSocket.accept();
// it more convenient to use DataInputStream instead of Scanner I think
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got request: " + msg);
dataOutputStream.writeUTF("1-response");
dataOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
Second host example:
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("2-request");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got response: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
If you want one host talk to another over the server (broker), then you need plane java Sockets on hosts and ServerSocket on broker, and broker must transmit messages it received from one host to another. Examples:
Broker (run it in separate thread or process)
try {
List<Socket> sockets = new ArrayList<>();
ServerSocket serverSocket = new ServerSocket(5555);
// accepting connections from 2 clients
for (int i = 0; i < 2; i++) {
Socket socket = serverSocket.accept();
sockets.add(socket);
}
// streams for first host
InputStream hostOneInputStream = sockets.get(0).getInputStream();
DataInputStream hostOneDataInputStream = new DataInputStream(sockets.get(0).getInputStream());
DataOutputStream hostOneDataOutputStream = new DataOutputStream(sockets.get(0).getOutputStream());
// streams for second host
InputStream hostTwoInputStream = sockets.get(1).getInputStream();
DataInputStream hostTwoDataInputStream = new DataInputStream(sockets.get(1).getInputStream());
DataOutputStream hostTwoDataOutputStream = new DataOutputStream(sockets.get(1).getOutputStream());
while (!Thread.currentThread().isInterrupted()) {
if (hostOneInputStream.available() > 0) {
String msg = hostOneDataInputStream.readUTF();
System.out.println("got message from host 1: " + msg);
hostTwoDataOutputStream.writeUTF(msg);
hostTwoDataOutputStream.flush();
System.out.println("message " + msg + " sent to host two");
}
if (hostTwoInputStream.available() > 0) {
String msg = hostTwoDataInputStream.readUTF();
System.out.println("got message from host 2: " + msg);
hostOneDataOutputStream.writeUTF(msg);
hostOneDataOutputStream.flush();
System.out.println("message " + msg + " sent to host one");
}
}
} catch (IOException e) {
e.printStackTrace();
}
First host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("1");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Second host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
dataOutputStream.writeUTF("2");
dataOutputStream.flush();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
I am trying to implement multi threading with a client/server program I have been working on. I need to allow multiple clients to connect to the server at the same time. I currently have 4 classes: a Client, a Server, a Protocol and a Worker to handle the threads. The following code is what I have for those classes:
SocketServer Class:
public class SocketServer {
public static void main(String[] args) throws IOException {
int portNumber = 9987;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
Thread thread = new Thread(new ClientWorker(clientSocket));
thread.start(); //start thread
String inputLine, outputLine;
// Initiate conversation with client
Protocol prot = new Protocol();
outputLine = prot.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = prot.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("quit"))
break;
}
} 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());
}
}
}
SocketClient Class:
public class SocketClient {
public static void main(String[] args) throws IOException
{
String hostName = "localhost";
int portNumber = 9987;
try (
Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("quit"))
break;
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 " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Protocol Class:
public class Protocol {
private static final int waiting = 0;
private static final int sentPrompt = 1;
private int status = waiting;
public String processInput(String theInput) {
String theOutput = null;
if (status == waiting) {
theOutput = "Please enter what you would like to retrieve: 'customer' or 'product' ";
status = sentPrompt;
}
else if ( status == sentPrompt ) {
if ( theInput.equalsIgnoreCase("product")) {
File f = new File("product.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current product entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("customer")) {
File f = new File("customer.txt");
Scanner sc = null;
try {
sc = new Scanner(f);
} catch (FileNotFoundException ex) {
Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
}
while ( sc.hasNextLine() ) {
String line = sc.nextLine();
theOutput = "The current customer entries are : " + line;
}
return theOutput;
}
else if ( theInput.equalsIgnoreCase("quit")) {
return "quit";
}
else {
return "quit";
}
}
return theOutput;
}
}
The ClientWorker Class:
public class ClientWorker implements Runnable {
private final Socket client;
public ClientWorker( Socket client ) {
this.client = client;
}
#Override
public void run() {
String line;
BufferedReader in = null;
PrintWriter out = null;
try {
System.out.println("Thread started with name:"+Thread.currentThread().getName());
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while (true) {
try {
System.out.println("Thread running with name:"+Thread.currentThread().getName());
line = in.readLine();
//Send data back to client
out.println(line);
//Append data to text area
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
When I run the server and client, everything works fine as expected. Then when I try to run another client, it just hangs there and does not prompt the client to give a response. Any insight into what I am missing is greatly appreciated!
Your server code should address implement below functionalities.
Keep accepting socket from ServerSocket in a while loop
Create new thread after accept() call by passing client socket i.e Socket
Do IO processing in client socket thread e.g ClientWorker in your case.
Have a look at this article
Your code should be
ServerSocket serverSocket = new ServerSocket(portNumber);
while(true){
try{
Socket clientSocket = serverSocket.accept();
Thread thread = new ClientWorker(clientSocket);
thread.start(); //start thread
}catch(Exception err){
err.printStackTrace();
}
}
How many times does serverSocket.accept() get called?
Once.
That's how many clients it will handle.
Subsequent clients trying to contact will not have anybody listening to receive them.
To handle more clients, you need to call serverSocket.accept() in a loop.
I'm new in network developing in Java and I want to create a simple Socket server, that get values from client and collects all of them in ArrayList. I wrote an example code, but in server side it not collecting the strings. This is my server side:
Server
public class ServerSideSocket extends Thread{
private ServerSocket serverSocket;
private Socket socket;
private ArrayList<String> list = new ArrayList<String>();
DataInputStream inData;
DataOutputStream outData;
public ServerSideSocket(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
while(true) {
try{
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connected!" );
inData = new DataInputStream(socket.getInputStream());
outData = new DataOutputStream(socket.getOutputStream());
System.out.println(inData.readUTF());
list.add(inData.readUTF());
System.out.println("------------ VALUES ---------");
for (String value: list) {
System.out.println(value);
}
System.out.println("------------ END VALUES ---------");
outData.writeUTF("Message saved!");
outData.flush();
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inData.close();
outData.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
int port = 9999;
try {
Thread t = new ServerSideSocket(port);
t.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
and Client:
public class ClientSideSocket {
public static void main(String[] args) {
String serverName = "localhost";
int port = 9999;
String line = "";
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 out = client.getOutputStream();
DataOutputStream outData = new DataOutputStream(out);
InputStream in = client.getInputStream();
DataInputStream inData = new DataInputStream(in);
outData.writeUTF("Simple text");
outData.flush();
System.out.println("Response from server: " + inData.readUTF());
System.out.println("You can write more messages!");
System.out.println();
client.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
what is wrong in my code?
This happens because you try to read twice from the data stream by calling inData.readUTF() method. First call successfully reads data from the stream, but instead of saving result you try to perform another read 2 lines below.
readUTF() is blocking method and thus it waits for another portion of data which never comes from the same client. That's why your server hungs forever
What you want to do is to read once and store result into local variable:
String res = inData.readUTF();
list.add(res);
You are writing data once as "Simple Text" which you can read only once.
Where in your code you are first reading it
System.out.println(inData.readUTF());
list.add(inData.readUTF());
Instead of this you should first store it in a String and then use it.
String message = inData.readUTF();
System.out.println(message);
list.add(message);
I am trying to forward a message from a client to a server and again from that server to another server. For the first time it works fine but when I type second message its say "Unexpected exception: Connection refused" why is it so?
Here is the code
Client.java
import java.net.*;
import java.io.*;
public class Client {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
#SuppressWarnings("deprecation")
public Client(String serverName, int serverPort) {
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals("exit")) {
try {
line = console.readLine();
streamOut.writeUTF(line);
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void start() throws IOException {
console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
}
public void stop() {
try {
if (console != null)
console.close();
if (streamOut != null)
streamOut.close();
if (socket != null)
socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public static void main(String args[]) {
#SuppressWarnings("unused")
Client client = null;
if (args.length != 2)
System.out.println("Usage: java Client host port");
else
client = new Client(args[0], Integer.parseInt(args[1]));
}
}
AuServer.java
import java.net.*;
import java.io.*;
public class AuServer {
private Socket socket = null;
private Socket publishingsocket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
private String line = null;
private DataOutputStream streamOut = null;
public AuServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done) {
try {
line = streamIn.readUTF();
System.out.println(line);
done = line.equals("exit");
} catch (IOException ioe) {
done = true;
}
forward(line, 50090);
}
close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void forward(String line, int port) {
try {
publishingsocket = new Socket("localhost", port);
streamOut = new DataOutputStream(publishingsocket.getOutputStream());
streamOut.writeUTF(line);
streamOut.flush();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
} finally {
try {
publishingsocket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
}
public static void main(String args[]) {
#SuppressWarnings("unused")
AuServer server = null;
if (args.length != 1)
System.out.println("Usage: java Server port");
else
server = new AuServer(Integer.parseInt(args[0]));
}
}
AppServer.java
import java.net.*;
import java.io.*;
public class AppServer {
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream streamIn = null;
public AppServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted: " + socket);
open();
boolean done = false;
while (!done) {
try {
String line = streamIn.readUTF();
System.out.println(line);
done = line.equals("exit");
} catch (IOException ioe) {
done = true;
}
}
close();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(
socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
}
public static void main(String args[]) {
#SuppressWarnings("unused")
AppServer server = null;
server = new AppServer(50090);
}
}
Pls help............
A typically socket server would require some kind of loop where in the server socket would accept incoming connections and spawn a new Thread which would be responsible for actually handling the new Socket connection, leaving the current thread free to continue processing any new incoming connections, for example...
server = new ServerSocket(port);
while (continueAccpetingConnections) {
Socket socket = server.accept();
Thread thread = new Thread(new SocketHandler(socket));
thread.start();
}
The SocketHandler would implement Runnable and provide a constructor that would accept a Socket variable.
It would then be the responsibility of the SocketHandler to actually perform the communications required by the server.
Now, if you wanted to have only one active connection, you might use
while (continueAccpetingConnections) {
Socket socket = server.accept();
process(socket);
}
Which would prevent any new connections until process returned...
Your server is written to accept exactly one connection, process it in the same thread, and then exit. If you want to keep accepting connections, do so, in a loop. If you want to handle clients concurrently, start a new thread to handle each accepted socket.