So I have a Server/Client layer app running between my application and database. I would like to get an array from the Server. I will paste some pieces of code which I think is enough to give you an idea of what is going on:
I send to the server the keyword for search in database (user and his password)
fromUser = Musername + "," + Password;
out.println(fromUser);
Here is the code of the Server:
public class Server {
public static String[] theOutput;
public static String inputLine;
public static String[] string_array;
public static String output = "";
public static String[] process(String Input) throws Exception {
String[] data = Input.split(",");
// Call database class to get the results and store them into the array
load_login pridobi = new load_login();
theOutput = pridobi.nalozi(data[0], data[1]);
return theOutput;
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
// get the username and password
inputLine = in.readLine();
if (inputLine.length() != 0) {
string_array = process(inputLine);
}
// And here I would like to do something like that :/
out.println(string_array);
}
}
PS: NOTE that some array elements are actually long text.
I recommended you use other technically.
what happended if username and password that you send to the server contain a ",".
When you split you obtain a wrong data.
Before send: Example:
String username = URLEncoder.encoder("myusername", "utf-8");
String password = URLEncoder.encoder("mypassword", "utf-8");
String dataToSend = username + "," + password;
In your server:
String[] data = Input.split(",");
data[0] = URLDecoder.decoder(data[0],"utf-8");
data[1] = URLDecoder.decoder(data[1],"utf-8");
The server should response a string like this:
String responseData = URLEncoder.encoder(theOutput[0], "utf-8") + "," + URLEncoder.encoder(theOutput[1], "utf-8");
out.println(responseData);
The client side read the response like this:
String dataReceived = inputLine = in.readLine();
String data[] = dataReceived.split(",");
data[0] = URLDecoder.decoder(data[0],"utf-8");
data[1] = URLDecoder.decoder(data[1],"utf-8");
Related
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);
}
}
}
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?
I am trying to send an ArrayList to a client on an android device. The server says it sent the object however on the android device it hangs. I have read around that when creating an ObjectInputStream, an ObjectOuputStream must be created first and then flushed. I have tried that however this is not working for me. I didn't post the code for getting the clients as its just simply reading from a textfile. The Client class is very basic with few properties such as username, password and friends arraylist of strings. Any help would be much appreciated.
Server:
public class Server {
private static final int port = 9001;
private static final String IPAddr = "xxxxxxxxxxx";
ServerSocket server = null;
ArrayList <Client> users = new ArrayList<Client>();
public Server(){
try{
server = new ServerSocket(port);
System.out.println("connected server on port" + port);
while(true){
System.out.println("waiting for connection my ip add is "+ InetAddress.getLocalHost().getHostAddress());
Socket clientsocket = server.accept();
System.out.println("Connect to client:"+ clientsocket.getInetAddress().getHostName());
ClientThread client = new ClientThread(clientsocket);
client.start();
}
} catch(IOException e) {
System.err.println("Could not listen on port");
}
}
//Thread
public class ClientThread extends Thread {
private Socket sckt = null;
public ClientThread(Socket sckt){
super("ClientThread");
this.sckt = sckt;
}
public void run(){
try{
PrintWriter out = new PrintWriter(sckt.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
ObjectOutputStream objectOutput = new ObjectOutputStream(sckt.getOutputStream());
objectOutput.flush();
String Username = input.readLine();
String Password = input.readLine();
System.out.println("recieved from client: "+ Username);
int ClientIndex = isClient(Username);
if (ClientIndex != -1){
if(users.get(ClientIndex).password.equals(Password)){
//password correct -> send friends
out.println("correct");
out.flush();
System.out.println(Username + " is correct");
LoadClientFriends(Username, ClientIndex);
objectOutput.writeObject(users.get(ClientIndex).Friends);
System.out.println("Friends sent");
} else {
//password incorrect -> retry
out.println("password");
System.out.println(Username + " has wrong password");
}
} else {
//not a registered client
out.println("wrong");
System.out.println(Username + " is not a client");
}
} catch(Exception e){
System.err.println("Couldnt connect to Client socket");
}
}
}
public static void main(String[] args){
Server svr = new Server();
}
}
Client/Android:
public class MainActivity extends ActionBarActivity {
//Varibles
EditText username;
EditText password ;
private static final int port = 9001;
private static final String IPAddr = "xxxxxxx";
//Methods
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
/* Drawable d = getResources().getDrawable(R.drawable.actionbar_background);
getActionBar().setBackgroundDrawable(d);*/
}
public void Login(View view) {
//connect to server
Thread myThread2 = new Thread(Connect);
myThread2.start();
}
public void Register(View view) {
Intent i = new Intent(this, register_screen.class);
startActivity(i);
}
Runnable Connect = new Runnable()
{
public void run()
{
try {
Socket connection = new Socket(IPAddr,port);
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter output = new PrintWriter(connection.getOutputStream(), true);
//Sent the username a password for verifaction
username = (EditText)findViewById(R.id.edtName);
password = (EditText)findViewById(R.id.edtPassword);
output.println(username.getText().toString());
output.flush();
output.println(password.getText().toString());
output.flush();
//Receive confirmation of client
String res = input.readLine();
if (res.contains("correct")){
ObjectOutputStream objectOutput = new ObjectOutputStream(connection.getOutputStream());
objectOutput.flush();
ObjectInputStream objectInput = new ObjectInputStream(new BufferedInputStream(connection.getInputStream())); //Error Line!
Object object = objectInput.readObject();
ArrayList<String> friends = (ArrayList<String>) object;
Intent intent = new Intent(MainActivity.this,chat_screen.class);
intent.putExtra("Friends", friends);
startActivity(intent);
}else if (res.contains("password")){
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
}else {
}
}catch (Exception e){
}
}
};
}
The error you see is due to multiple output stream format. Stick to either ObjectOutputStream/ObjectInputStream or PrintWriter/BufferedReader. I suggest ObjectOutputStream/ObjectInputStream.
Server code: Use objectOutPut for all writes.
// out.println("correct");
objectOutput.writeUTF("correct");
// Update code for password and wrong too - Use objectOutput.writeUTF("");
Client code: Use just ObjectInputStream instead of BufferedReader
Define the objectInput here instead:
// BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ObjectInputStream objectInput = new ObjectInputStream(connection.getInputStream());
PrintWriter output = new PrintWriter(connection.getOutputStream(), true);
// Read data as follows:
// String res = input.readLine();
String res = objectInput.readUTF();
I am pretty new to Java and know nothing about ports or servers or sockets so i was hoping someone could help me. I want to make a little program that will print all the messages in your inbox (read and unread).
I found this code online but it only gives me my earliest message in my sent folder.
public class EmailService {
String server = "pop.gmail.com";
int port = 995;
static String username;
static String password;
SSLSocket socket;
BufferedReader input;
PrintWriter output;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
username = s.next() + "#gmail.com";
password = s.next();
new EmailService();
}
public EmailService() {
try {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
socket = (SSLSocket)sslsocketfactory.createSocket(server, port);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// After each println you MUST flush the buffer, or it won't work properly.
// The true argument makes an automatic flush after each println.
output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
connect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void connect() throws IOException {
System.out.print("Greeting message: ");
String response = readOneLine();
System.out.println(response);
// Username
output.println("USER " + username);
response = readOneLine();
System.out.println(response);
// Password
output.println("PASS " + password);
response = readOneLine();
System.out.println(response);
output.println("RETR 1");
while (!response.equals(".")) {
response = readOneLine();
System.out.println(response);
}
}
public String readOneLine() throws IOException {
return input.readLine();
}
}
How would I change this code to get me all the messages in my inbox?
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);
}