Server-Client chat program - java

I am writing a server-client chat program.
Here is my code
SERVER:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
String response = "Hello " + s.getInetAddress() + " on port " + s.getPort()
+ "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort()
+ "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
System.out.write(response.getBytes());
InputStream in = s.getInputStream();
System.out.println("from client");
int z = 0;
while ((z = in.read()) != -1) {
System.out.write(z);
}
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
CLIENT:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("192.xxx.x.xxx", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
+ socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
int b = 0;
OutputStream os = System.out;
while ((b = bfINPUT.read()) != -1) {
os.write(b);
}
OutputStream osNew = socket.getOutputStream();
String s = "This Is The Client"; // data to be sent
osNew.write(s.getBytes());
os.write(s.getBytes());
}
I've connected them through my program.
But now I want to know How to send some data back to the server from client?
What would be the code for client(for sending data to server) and also the code for the server for showing the data received from the client on the console(server)?
P.S- I am a novice in network programming. Please do not criticize my coding style :P

Use server stream
OutputStream os = socket.getOutputStream();
instead of client console output stream
OutputStream os = System.out;
at client side to write back to server.
and at server side use client stream to read from client in the same manner.
InputStream in = s.getInputStream();
I have already posted a sample code on server-client communication. Read it for your learning.

You need threads. The client in this examples read the lines from the System.in and sends the line to the server. The server sends an echo.
In your real application you have to take a look of the encoding
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
new SocketThread(s).start();
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public static class SocketThread extends Thread {
private Socket s;
public SocketThread(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "Hello " + s.getInetAddress() + " on port "
+ s.getPort() + "\r\n";
response += "This is " + s.getLocalAddress() + " on port "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true) {
String line = input.readLine();
System.out.println("IN: " + line);
s.getOutputStream().write(("ECHO " + line + "\n").getBytes());
s.getOutputStream().flush();
System.out.println(line);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: " + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
new OutputThread(socket.getInputStream()).start();
InputStreamReader consoleReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(consoleReader);
while (true) {
String inline = in.readLine();
if (inline.equals("by")) {
break;
}
inline += "\n";
socket.getOutputStream().write(inline.getBytes());
socket.getOutputStream().flush();
}
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
#Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}
}
}

Related

Java basic concurrent communicator - does not fully accept connection

I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.

Multi Client Simple Chat(non-GUI) Server in Java using threads

I am unable to figure out how to stop the message from appearing twice on both the client's screen.
The Actual output should be something like this:
Steps for Running the code:
1. Run Server on one terminal
2. Run two clients on two different terminals
When I run the Server - main method creates a Server object:
public static void main(String[] args) throws IOException {
Server server = new Server();
}
Server Constructor:
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
I am using Socket to connect to the server. Here is my Server code.
Server.java
import java.io.IOException;
import java.net.*;
import java.util.Vector;
import java.io.*;
import java.util.*;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.*;
import java.util.Scanner;
public class Server {
static Vector<Socket> ClientSockets;
int clientCount = 0;
//int i = 0;
Server() throws IOException {
Date dNow = new Date();
System.out.println("MultiThreadServer started at " + String.format("%tc", dNow));
System.out.println();
ServerSocket server = new ServerSocket(8000);
ClientSockets = new Vector<Socket>();
while (true) {
Socket client = server.accept();
AcceptClient acceptClient = new AcceptClient(client);
System.out.println("Connection from Socket " + "[addr = " + client.getLocalAddress() + ",port = "
+ client.getPort() + ",localport = " + client.getLocalPort() + "] at "
+ String.format("%tc", dNow));
System.out.println();
//System.out.println(clientCount);
}
//server.close();
}
public static void main(String[] args) throws IOException {
Server server = new Server();
}
class AcceptClient extends Thread {
Socket ClientSocket;
DataInputStream din;
DataOutputStream dout;
AcceptClient(Socket client) throws IOException {
ClientSocket = client;
din = new DataInputStream(ClientSocket.getInputStream());
dout = new DataOutputStream(ClientSocket.getOutputStream());
//String LoginName = din.readUTF();
//i = clientCount;
clientCount++;
ClientSockets.add(ClientSocket);
//System.out.println(ClientSockets.elementAt(i));
//System.out.println(ClientSockets.elementAt(1));
start();
}
public void run() {
try {
while (true) {
String msgFromClient = din.readUTF();
System.out.println(msgFromClient);
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
DataOutputStream pOut = new DataOutputStream(pSocket.getOutputStream());
pOut.writeUTF(msgFromClient);
pOut.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Client.java
import java.net.Socket;
import java.util.Scanner;
import java.io.*;
import java.net.*;
public class Client implements Runnable{
Socket socketConnection;
DataOutputStream outToServer;
DataInputStream din;
Client() throws UnknownHostException, IOException {
socketConnection = new Socket("127.0.0.1", 8000);
outToServer = new DataOutputStream(socketConnection.getOutputStream());
din = new DataInputStream(socketConnection.getInputStream());
Thread thread;
thread = new Thread(this);
thread.start();
BufferedReader br = null;
String ClientName = null;
Scanner input = new Scanner(System.in);
String SQL = "";
try {
System.out.print("Enter you name: ");
ClientName = input.next();
ClientName += ": ";
//QUERY PASSING
br = new BufferedReader(new InputStreamReader(System.in));
while (!SQL.equalsIgnoreCase("exit")) {
System.out.println();
System.out.print(ClientName);
SQL = br.readLine();
//SQL = input.next();
outToServer.writeUTF(ClientName + SQL);
//outToServer.flush();
//System.out.println(din.readUTF());
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] arg) throws UnknownHostException, IOException {
Client client = new Client();
}
public void run() {
while (true) {
try {
System.out.println("\n" + din.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The reason you have this is because you're sending the server whatever the client has written in the console, and the server sends it back to all of the clients (including the sender).
So you're writing a message in the console (and you see it) and then you're receiving it back as one of the clients (and you see it again).
A simple fix would be not to send the just received message back to the client (he already sees it in the console). Add this to the Server.AcceptClient#run method:
for (int i = 0; i < ClientSockets.size(); i++) {
Socket pSocket = (Socket) ClientSockets.elementAt(i);
if(ClientSocket.equals(pSocket)){
continue;
}
...

Why the socket is always close when i send the data in java TCP

server class :
the program is about to receive data from client and then reply. the server is okay..., but the problem is when the server send the reply to the client. the client always says 'the socket is close'. i try to delete secket close statement but the result is same.., the output says that 'the socket is close'. so please help me to solve this problem...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
public class Nomor3Server {
public static final int SERVICE_PORT = 2020;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(SERVICE_PORT);
System.out.println("DAytime service started");
for (;;) {
Socket nextClient = server.accept();
BufferedReader pesan = new BufferedReader(new InputStreamReader(nextClient.getInputStream()));
String messageIn = pesan.readLine();
System.out.println("Received request from "
+ nextClient.getInetAddress() + " : "
+ nextClient.getPort()
+ "\nIsi Pesan : " + messageIn);
String messageOut = "انا لا ادر";
switch (messageIn) {
case "saya":
messageOut = "أنا";
break;
case "kamu":
messageOut = "أنت";
break;
default:
break;
}
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(messageOut);
out.flush();
out.close();
System.out.println("Message sent");
//nextClient.close();
}
} catch (BindException e) {
System.err.println("Server Already Running on port : " + SERVICE_PORT);
} catch (IOException ioe) {
System.err.println("error : " + ioe);
}
}
}
client class :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
public class Nomor3Client {
public static final int SERVICE_PORT = 2020;
public static void main(String[] args) {
try {
String hostname = "localhost";
System.out.println("Connection Established");
//for (;;) {
System.out.println("Enter Your Message : ");
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String pesan = read.readLine();
Socket daytime = new Socket(hostname, SERVICE_PORT);
if (pesan.equals("exit")) {
System.exit(0);
} else {
daytime.setSoTimeout(2000);
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close();
BufferedReader messageIn = new BufferedReader(new InputStreamReader(daytime.getInputStream()));
System.out.println("Respond : " + messageIn.readLine());
System.out.println("diterima");
}
daytime.close();
//}
} catch (IOException e) {
System.err.println("Error : " + e);
}
}
}
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close();
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#getOutputStream()
Closing the returned OutputStream will close the associated socket.
Socket get closed in such situations:
when you close the socket,
when you close the input or the output socket stream,
when you close the object, which is directly or indirectly wrapping the input or the output socket stream, e.g. BufferedReader or Scanner.
Server Class
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(messageOut);
out.flush();
out.close(); //Don't close this
Client Code :
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close(); //Don't close this

Corrupted inputStream

It errors at the last line in the client code, with the code. java.io.StreamCorruptedException: invalid stream header: 36353137. I haven't done anything to the stream before this point, so I am unsure what could be causing the problem with the ObjectInputStream.
The server class works properly, and follows the behavior I set for it, it is only the client class that is erroring.
I thought the problem at first might be because the stream wasn't being flushed, but flushing it did not fix the issue.
Apart from that, since this error is happening so early in the code, I am at a loss as to what to add to fix it.
Client class -
import java.io.*;
import java.net.*;
public class tcpClient {
int nonce;
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
tcpClient(){}
void run()
{
try{
requestSocket = new Socket("localhost", 3223);
System.out.println("Connected to localhost in port 3223");
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
Server Class -
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.Timer;
public class TCPMasterServer
implements ActionListener
{
ServerSocket server;
Socket client;
Random random;
Calendar rightNow;
Timer timer;
String ipaddress;
PrintWriter out;
BufferedReader ir;
public TCPMasterServer()
{
this.random = new Random();
this.rightNow = Calendar.getInstance();
try
{
this.server = new ServerSocket(3223);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void listenForConnection()
{
try
{
this.client = this.server.accept();
this.ipaddress = this.client.getInetAddress().getHostAddress();
System.out.println(this.rightNow.getTime() + ": Connected from: " + this.ipaddress);
this.out = new PrintWriter(this.client.getOutputStream(), true);
this.ir = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
communicateWithClient();
}
catch (Exception e)
{
e.printStackTrace();
listenForConnection();
}
}
private void communicateWithClient()
{
this.timer = new Timer(2000, this);
this.timer.setRepeats(false);
this.timer.start();
try
{
int nonce = this.random.nextInt(1000000);
this.out.println(nonce);
System.out.println(this.rightNow.getTime() + ": Send nonce: " + nonce);
String input = this.ir.readLine();
Scanner in = new Scanner(input);
int nonceResponse = in.nextInt();
System.out.print(this.rightNow.getTime() + ": Received number: " + nonceResponse);
if (nonceResponse == nonce + 1)
{
System.out.println("... OK");
this.out.println("SEND_NAME");
System.out.println(this.rightNow.getTime() + ": Request name");
input = this.ir.readLine();
System.out.println(this.rightNow.getTime() + ": Received name: " + input);
this.out.println(input + " ACK");
System.out.println(this.rightNow.getTime() + ": ACK sent");
}
this.client.close();
}
catch (Exception ex)
{
System.out.println(this.rightNow.getTime() + ": Error happened. Giving up");
}
this.timer.stop();
System.out.println();
listenForConnection();
}
public void actionPerformed(ActionEvent evt)
{
try
{
System.out.println("Timer fired.");
this.client.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
TCPMasterServer server = new TCPMasterServer();
server.listenForConnection();
}
}
You're using object streams at the server, but readers and writers at the client. That won't work. If you want to read objects you must write objects.

Java server , client program

The code below should allow the user to enter a URL and have it return the ip address of that website but it's not working.
The application is a console application. I had it working at one time but I don't know why it won't work now.
Here is the error i am getting when the users enters a website to get the ip address from
IOException: java.net.SocketException: Connection reset
HERE IS MY CLIENT CODE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6052;
if (args.length > 0) {
hostname = args[0];
}
Socket clientSocket = null;
PrintWriter os = null;
BufferedReader is = null;
try {
clientSocket = new Socket(hostname, port);
os = new PrintWriter(clientSocket.getOutputStream(), true);
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
if (clientSocket == null || os == null || is == null) {
System.err.println("Something is really wrong. ");
return;
}
try {
if (args.length != 2) {
System.out.print("Enter a www web address (must have www!) ");
BufferedReader br = new BufferedReader(new InputSreamReader(Sy.in))
String keyboardInput = br.readLine();
os.println(keyboardInput);
} else {
os.println(args[1]);
}
String responseLine = is.readLine();
System.out.println("The IP address of " + args[1] + "is" + responseLine);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
HERE IS MY SERVER CODE
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
int port = 6052;
Server server = new Server(port);
server.startServer();
}
ServerSocket echoServer = null;
Socket clientSocket = null;
int numConnections = 0;
int port;
public Server(int port) {
this.port = port;
}
public void stopServer() {
System.out.println("Server working hold on a min.");
System.exit(0);
}
public void startServer() {
try {
echoServer = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Server is now started and is waiting for Clients.");
while (true) {
try {
clientSocket = echoServer.accept();
numConnections++;
new Thread(new ServerConnection(clientSocket, numConnections,
this)).start();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class ServerConnection implements Runnable {
private static BufferedReader is;
private static PrintStream os;
private static Socket clientSocket;
private static int id;
private static Server server;
public ServerConnection(Socket clientSocket, int id, Server server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println( "Connection " + id + " established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
line = is.readLine();
System.out.println( "Received " + line + " from Connection " + id + "." );
InetAddress hostAddress = InetAddress.getByName(line);
String IPaddress = hostAddress.getHostAddress();
os.println(IPaddress);
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
With no arguments, host will be localhost, user will be propted for a website. ArrayOutOfBoundsException because you didn't check the arguments.
With one argument, it is the host. Passing a site will not work because the site won't work as expected.
Running with two arguments, it works if the first argument is localhost.

Categories