I have written a program to send current IP between my servers using TCP/IP. when I run the program in IDE everything works fine and I get the expected result but when I package it using Maven, the program runs only once and immediately jumps out of the loop. can anyone help me understand why this is happening?
public String getIP () throws UnknownHostException {
InetAddress myIP=InetAddress.getLocalHost();
//System.out.println("My IP Address is:");
//System.out.println(myIP.getHostAddress());
String IP = myIP.getHostAddress();
return IP;
}
public String getID(){
JFrame f;
f=new JFrame();
String ID=JOptionPane.showInputDialog(f,"Enter GSID");
return ID;
}
public static void main(String args[]) throws IOException, InterruptedException {
Socket s1 = null;
BufferedReader br = null;
BufferedReader is = null;
PrintWriter pwr = null;
client obj = new client();
String CID = obj.getID();
String response = null;
while(true) {
String ServerIP = "173.16.1.5";
s1 = new Socket(ServerIP, 4445);
br = new BufferedReader(new InputStreamReader(System.in));
is = new BufferedReader(new InputStreamReader(s1.getInputStream()));
pwr = new PrintWriter(s1.getOutputStream());
// send ID to Server
pwr.println(CID);
pwr.flush();
response = is.readLine();
System.out.println("Server Response : " + response);
// get IP and send to Server
client IP = new client();
String CIP = IP.getIP();
pwr.println(CIP);
pwr.flush();
response = is.readLine();
System.out.println("Server Response : " + response);
// send time
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
pwr.println(dtf.format(now));
pwr.flush();
response = is.readLine();
System.out.println("Server Response : " + response);
is.close();
pwr.close();
br.close();
s1.close();
System.out.println("Connection Closed");
JFrame f;
f=new JFrame();
TimeUnit.SECONDS.sleep(10);
}
}
}
Related
I am using reader.readLine() and sc.nextLine() to simulate the server and client. However, after I typed some words in the scanner, the server responded nothing. I think the problem is thread blocking, but I can't correct it. Could any one help point out where the sticking point is.
Here is the code for server.
public class Server {
public static LocalDateTime currentTime() {
return LocalDateTime.now();
}
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = new ServerSocket(9091);
System.out.println("TCP server ready.\n");
Socket sock = ss.accept();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))) {
String cmd;
System.out.println("read in");
while ((cmd = reader.readLine()) != null) {
System.out.println("Rcvd: " + cmd);
if ("time".equals(cmd)) {
writer.write(currentTime() + "\n");
writer.flush();
} else {
writer.write("Sorry?\n");
writer.flush();
}
}
}
}
sock.close();
ss.close();
}
}
The code for client
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
InetAddress addr = InetAddress.getLoopbackAddress();
try (Socket sock = new Socket(addr, 9091)){
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))){
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))){
Scanner sc = new Scanner(System.in);
String cmd;
while (sc.hasNext()) {
cmd = sc.nextLine();
System.out.println("Scanned: " + cmd);
writer.write(cmd);
writer.flush();
String resp = reader.readLine();
System.out.println("Response: " + resp);
}
}
}
}
Use this in Client:
writer.write(cmd + "\n");
since the server read lines.
I am creating a chat program between a server and a client but is run by a main function file.
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
All three files need to be able to access String args[] in the main function file because that is how it gets the port number
Right now the program is able to send and receive one message at a time successfully (see screenshot)
What changes can I make to the code that will allow me to send and receive multiple messages? (probably involves the use of java threads)
Code of main function file:
import java.io.IOException;
public class MainThread
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
}
i=args.length + 20;
}
}
}
Code of Server File:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class ServerThread
{
private String[] serverArgs;
public Socket socket;
public boolean keepRunning = true;
int ConnectOnce = 0;
public ServerThread(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
//run method of ServerRecieve
public void run() throws IOException
{
try
{
if(ConnectOnce == 0)
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
ConnectOnce = 4;
}
while(keepRunning)
{
//Reading the message from the client
//BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
//Run method of ServerSend
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Code of Client file:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class ClientThread implements Runnable
{
int ConnectOnce = 0;
private String[] clientArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public ClientThread(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
if(ConnectOnce == 0)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
ConnectOnce = 4;
}
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
#Override
public void run()
{
// TODO Auto-generated method stub
}
}
Currently I can only send and receive one line of text at a time, what changes can I make to the code that will allow me to send and receive multiple messages?
I am trying to create a text messaging program with three files (main function file, client file, server file)
If "-l" is present on the command line, it will run as a server, otherwise it will run as a client
Command line arguments to run server:
java DirectMessengerCombined -l 3000
Command line arguments to run client:
java DirectMessengerCombined 3000
Text of error:
java.net.BindException: Address already in use
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at java.net.ServerSocket.<init>(ServerSocket.java:128)
at DirectMessengerServer.run(DirectMessengerServer.java:41)
at DirectMessengerServer.runSend(DirectMessengerServer.java:111)
at DirectMessengerServer.run(DirectMessengerServer.java:58)
at DirectMessengerServer.<init>(DirectMessengerServer.java:16)
at DirectMessengerCombined.main(DirectMessengerCombined.java:21)
Screenshot of error (server on left, client on right):
The problem with the screenshot is that the left window (server) was able to send and recieve text messages to the client until the server sends the "hello" message.
Code of main Server file:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.IIOException;
public class DirectMessengerServer
{
private String[] serverArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public DirectMessengerServer(String[] args) throws IOException
{
// set the instance variable
this.serverArgs = args;
run();
}
public String[] ServerRun(String[] args) throws IOException
{
//How do I get the String[] args in this method be able to access it in the run methods?
serverArgs = args;
serverArgs = Arrays.copyOf(args, args.length);
return serverArgs;
}
Thread ListeningLoop = new Thread();
//run method of ServerRecieve
public void run() throws IOException
{
try
{
int port_number1 = Integer.valueOf(serverArgs[1]);
ServerSocket serverSocket = new ServerSocket(port_number1);
socket = serverSocket.accept();
while(keepRunning)
{
//Reading the message from the client
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClient = br.readLine();
System.out.println("Message received from client: "+ MessageFromClient);
// ServerSend.start();
runSend();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
Thread ServerSend = new Thread ();
//Run method of ServerSend
public void runSend()
{
while(keepRunning)
{
System.out.println("Server sending thread is now running");
try
{
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to client: "+sendMessage);
run();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
}
}
Code of Client file:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
private String[] clientArgs; // <-- added variable
private static Socket socket;
public boolean keepRunning = true;
public DirectMessengerClient(String[] args) throws IOException
{
// set the instance variable
this.clientArgs = args;
run(args);
}
public String[] ClientRun(String[] args)
{
clientArgs = args;
clientArgs = Arrays.copyOf(args, args.length);
return clientArgs;
}
Thread ClientSend = new Thread();
public void run(String args[]) throws IOException
{
System.out.println("Client send thread is now running");
while(keepRunning)
{
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
String line = "";
line= input.readLine();
newmessage += line + " ";
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n");
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
runClientRead(args);
}
}
Thread ClientRead = new Thread();
public void runClientRead(String args[]) throws IOException
{
System.out.println("Client recieve/read thread is now running");
//Integer port= Integer.valueOf(args[0]);
//String host = "localhost";
//InetAddress address = InetAddress.getByName(host);
//socket = new Socket(address, port);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
}
}
Code of main function file:
import java.io.IOException;
public class DirectMessengerCombined
{
public static void main(String[] args) throws IOException
{
DirectMessengerClient client1 = null;
DirectMessengerServer server1 = null;
for (int i = 0; i < args.length; i++)
{
if (args.length == 1)
{
client1 = new DirectMessengerClient(args);
client1.ClientRun(args);
}
else if (args.length == 2)
{
server1 = new DirectMessengerServer(args);
server1.ServerRun(args);
}
i=args.length + 20;
}
}
}
My question is not only how to resolve the error (there's plenty of other questions that covered this) but why wasn't the error triggered the first time the messages were sent/received to/from the server?
public class JavaApplication15 {
public static String ip="127.0.0.1";
public static int port=5060;
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
InetAddress ii = InetAddress.getLocalHost();
System.out.println(ii);
InetAddress ad = InetAddress.getByName(ip);
System.out.println(ad);
InetAddress i = ad;
System.out.println(i);
try {
// TODO code application logic here
ss = new ServerSocket();
ss.bind(new InetSocketAddress(ip, port));
InetSocketAddress ia;
String st=ss.getLocalSocketAddress().toString(); // print socket ip and address
System.out.println(st);
System.out.println("created");
} catch (IOException ex) {
System.out.println("not created");
}
Socket client = null,ee = null;
client = ss.accept();
PrintWriter out = null;
BufferedReader in = null ;
out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String input = null;
while((input = in.readLine())!=null){
System.out.println(input);
System.out.println("echo :" +in.readLine());
}
out.flush();
in.close();
stdin.close();
client.close();
ss.close();
}
}
}
In this code server is being created and trying to establish a connection with socket. I think this code should show output but it is not showing. For example: if i say hello in the console , it should print hello. But it is not doing that. Can anyone help me what is actually going on here ???
I have written the code which have to find the file size using http HEAD request through sockets... i try it in my home with non proxy connection its working ... but when i try it in my college with a proxy server whose ip is 172.16.4.6 and port 1117 it is not working......any suggestion......thanks.
public class Proxytesting {
private static OutputStream os;
private static InputStream in;
private static BufferedReader reader;
private static int Totalsize;
public static void main(String[] args) {
try {
URL url_of_file=new URL("http://www.stockvault.net/data/s/124348.jpg");
String hostaddress=url_of_file.getHost();
////////////////////for proxy server ///////////////////
String textip="172.16.4.7";
InetAddress host=InetAddress.getByName(textip);
System.out.println(host);
int port=1117;
SocketAddress ad=new InetSocketAddress(host, 1117);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, ad);
Socket mysocket2 = new java.net.Socket();
mysocket2.connect(new InetSocketAddress(hostaddress,80));
System.out.println("Socket opened to " + hostaddress + "\n");
String file=url_of_file.getFile();
System.out.println(" file = "+file);
os = mysocket2.getOutputStream();
String headRequest = "HEAD " +url_of_file+" HTTP/1.1\r\n"
+ "Host: "+ hostaddress +"\r\n\r\n";
os.write(headRequest.getBytes());
in = mysocket2.getInputStream();
reader= new BufferedReader(new InputStreamReader(in));
String contlength="Content-Length:";
// 1. Read the response header from server separately beforehand.
String response;
Totalsize = 0;
do{
response = reader.readLine();
if(response.indexOf("Content-Length") > -1)
{
Totalsize = Integer.parseInt(response.substring(response.indexOf(' ')+1));
response = null;
}
}while(response != null);
System.out.println(" cont_lentht ##### == "+Totalsize);
} catch (IOException ex) {
Logger.getLogger(Proxytesting.class.getName()).log(Level.SEVERE, null, ex);
}
The error I get is:
Unknown host exception at for code [ mysocket2.connect(
new InetSocketAddress(hostaddress,80));]
You are making things very hard for yourself. Use HttpURLConnection to connect through the proxy:
HttpConnection conn = (HttpConnection) url_of_file.openConnection(proxy);
conn.setRequestMethod("HEAD");
Totalsize = conn.getContentLength();
There are other HTTP clients which do a better job, but you should not create your own unless existing clients don't do what you need!
Thanks for the clues in comments. I found the solution to the problem. There was a bug in the code I was constructing InetSocketAddress twice using a wrong port. The complete working code is below.
public class Proxytesting {
private static OutputStream os;
private static InputStream in;
private static BufferedReader reader;
private static int Totalsize;
public static void main(String[] args) {
try {
URL url_of_file=new URL("http://www.stockvault.net/data/s/124348.jpg");
String hostaddress=url_of_file.getHost();
////////////////////for proxy server ///////////////////
String textip="172.16.4.7";
InetAddress host=InetAddress.getByName(textip);
System.out.println(host);
int port=1117;
SocketAddress ad=new InetSocketAddress(host, 1117);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, ad);
Socket mysocket2 = new java.net.Socket();
mysocket2.connect(ad);
System.out.println("Socket opened to " + hostaddress + "\n");
String file=url_of_file.getFile();
System.out.println(" file = "+file);
os = mysocket2.getOutputStream();
String headRequest = "HEAD " +url_of_file+" HTTP/1.1\r\n"
+ "Host: "+ hostaddress +"\r\n\r\n";
os.write(headRequest.getBytes());
in = mysocket2.getInputStream();
reader= new BufferedReader(new InputStreamReader(in));
String contlength="Content-Length:";
// 1. Read the response header from server separately beforehand.
String response;
Totalsize = 0;
do{
response = reader.readLine();
if(response.indexOf("Content-Length") > -1)
{
Totalsize = Integer.parseInt(response.substring(response.indexOf(' ')+1));
response = null;
}
}while(response != null);
System.out.println(" cont_lentht ##### == "+Totalsize);
} catch (IOException ex) {
Logger.getLogger(Proxytesting.class.getName()).log(Level.SEVERE, null, ex);
}