I have written a TCP Client program which calls the properties file and takes the values from there. When I run the TCPClient for the first time, it runs properly and sends all the data values of server.properties file to the server, but as soon as I try to add one more data "data4" to server.properties file my project gets a "x" mark and the changes made in server.properties file don't reflect and I get Error: cannot find or load class TCPClient.
I tried to create a new project, still the same, the changes made to properties file do not reflect. Can someone kindly help me on this. Thanks in advance
public class TCPClient {
private static Socket socket;
public String getPropertyValues() throws IOException{
String result="";
Properties prop = new Properties();
String propFileName = "server.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
try
{
String host = prop.getProperty("host");
System.out.println(host);
int port = Integer.parseInt(prop.getProperty("port"));
System.out.println(port);
String data = prop.getProperty("data");
System.out.println(data);
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);
String sendMessage = data;
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) throws IOException{
TCPClient properties = new TCPClient();
properties.getPropertyValues();
}
}
I have a properties file by name server.properties
data = data1
data2
data3
port = 3035
host = localhost
When ever I make change to the data field of this properties file and save, the project turns with a "x" mark and when I try to run the TCPClient program using Run as-->JavaApplication, I get the pop up as
Errors exist in required project
Test
Proceed with Launch?
Related
I am trying to send a file over a TCP socket from a Java Client to a Python Server. I have been able to successfully transfer the file, but there is a problem with the server where it fails to recognize the end of the byte stream it is receiving from the client.
Here is my server:
import socket
server_addr = '127.0.0.1', 5555
# Create a socket with port and host bindings
def setupServer():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created")
try:
s.bind(server_addr)
except socket.error as msg:
print(msg)
return s
# Establish connection with a client
def setupConnection(s):
s.listen(5) # Allows five connections at a time
print("Waiting for client")
conn, addr = s.accept()
return conn
def getFile(filename, conn):
print("Creating file", filename, "to write to")
with open(filename, 'wb') as f:
data = conn.recv(1024)
while data:
print(data)
f.write(data)
data = conn.recv(1024) #This is where the problem is
print("Finished writing to file")
# Loop that sends & receives data
def dataTransfer(conn, s):
while True:
# Recieve a file
print("Connected with:", s)
filename = "test.json"
getFile(filename, conn)
break
conn.close()
sock = setupServer()
while True:
try:
connection = setupConnection(sock)
dataTransfer(connection, sock)
except:
break
And here is the Java Client:
import java.io.*;
import java.net.*;
public class Client1
{
private Socket socket = null;
private FileOutputStream fos = null;
private DataInputStream din = null;
private DataOutputStream dos = null;
private PrintStream pout = null;
public Client1(InetAddress address, int port)
{
try {
System.out.println("Initializing Client");
socket = new Socket(address, port);
din = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
pout = new PrintStream(socket.getOutputStream());
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(1);
}
}
public void send(String msg) throws IOException
{
pout.print(msg);
pout.flush();
}
public void closeConnections() throws IOException
{
// Clean up when a connection is ended
socket.close();
din.close();
dos.close();
pout.close();
scan.close();
}
public void sendFile(String filename)
{
System.out.println("Attempting to send file: "+filename);
try{
File file = new File(filename);
if(!file.exists()){
System.out.println("File does not exist. Aborting");
return;
}
//send(filename);
try (FileInputStream fis = new FileInputStream(file)) {
int count;
byte[] buffer = new byte[1024];
while( (count = fis.read(buffer)) > 0){
dos.write(buffer, 0 , count);
}
dos.flush();
}
} catch(IOException e){
e.printStackTrace();
}
}
}
The problem is the while loop in the server in the getFile() method. Specifically, the data = conn.recv(1024) inside the while loop seems to loop infinitely and data is never null. The while loop runs just the same as if it read while True: but it should break once the message ends and then close the connection. As I mentioned earlier, the data arrives correctly and the client exits cleanly, it's just that the server fails to detect that there is not more data incoming.
Any suggestions on how to get this loop working properly?
I have to write java project for TCP Client/Server. The goal of the code is the Client asks server about a file. if the file is available it will be saved into client directory and show message the file is found and saved otherwise, the file is not found.
the code works when the file is in the Server directory and it will be saved in the client directory but if the file is not available it will show message in server side the file not available but in Client side it will save a new empty file with the name of the file that not available and message the File received
Can you help please
I have Server code
import java.io.*;
import java.net.*;
import java.util.*;
//********************
public class Server
{
static ServerSocket ServSock;
static int QLen = 6;
//***
public static void main(String args[])
{
try
{
//*** establish server socket
ServSock = new ServerSocket(Integer.parseInt(args[0]), QLen);
while (true)
{
//*** accept a client
Socket Sock = ServSock.accept();
//*** pass the client to a new thread
new Worker(Sock).start();
}
}
catch(IOException e)
{System.out.println(e);}
}
}
//*************************
class Worker extends Thread
{
Socket Sock;
PrintWriter PW;
BufferedReader DIS;
String Question = "Enter the file name to transfer from server:";
//**************
Worker(Socket S)
{Sock=S;}
//**************
public void run()
{
try
{
//*** thread identifies itself
System.out.println("Thread: " + getName());
//*** auto-flush
//*** set up socket I/O streams
PW = new PrintWriter (new BufferedWriter (new OutputStreamWriter(Sock.getOutputStream())),true);
DIS = new BufferedReader (new InputStreamReader (Sock.getInputStream()));
//*** send server question
PW.println(Question);
//*** wait for client response
String R = DIS.readLine();
Scanner in = null;
try{
BufferedOutputStream put=new BufferedOutputStream(Sock.getOutputStream());
BufferedReader st=new BufferedReader(new InputStreamReader(Sock.getInputStream()));
String str = "/Users/Batool/Desktop/HW/Server/";
String path = str + R;
System.out.println("The requested file is path: "+path);
System.out.println("The requested file is : "+R);
File f=new File(path);
System.out.println(f.isFile());
if(f.isFile())
{
//System.out.println("inside if");
FileInputStream fis=new FileInputStream(f);
System.out.println("File transfered");
System.out.println("———————————————————————————————");
byte []buf=new byte[1024];
int read;
while((read=fis.read(buf,0,1024))!=-1)
{
put.write(buf,0,read);
put.flush();
}
}//end if
else{ System.out.println("File not found");
System.out.println("———————————————————————————————");}//end else
}//end try
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
//System.exit(0);
}//end catch
//*** close this socket connection
Sock.close();
}
catch(IOException e)
{System.out.println(e);}
}
}
and I have Client code
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
static Socket sock;
static PrintWriter pw;
static BufferedReader br;
static String response = "";
//************************************
public static void main(String args[]) throws IOException
{
//*** establish connection to remote server
sock = new Socket(args[0],
Integer.parseInt(args[1])); //*** provide server name & port
//*** set up socket I/O streams
pw = new PrintWriter (new BufferedWriter (new OutputStreamWriter(sock.getOutputStream())),true);
br = new BufferedReader (new InputStreamReader (sock.getInputStream()));
//*** wait for server question
String r = br.readLine(); //*** THIS IS A BLOCKING CALL
System.out.println("Server asks: " + r);
//*** respond to server
/*Scanner in = new Scanner(System.in);
String s = in.nextLine();
pw.println(s);
pw.flush();
*/
Socket s=null;
BufferedInputStream get=null;
PrintWriter put=null;
try
{
get=new BufferedInputStream(sock.getInputStream());
put=new PrintWriter(sock.getOutputStream(),true);
String f;
int u;
//System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
String str = "/Users/Batool/Desktop/HW/Client";
FileOutputStream fs=new FileOutputStream(new File(str,f1.toString()));
System.out.println(new File(str,f1.toString()));
System.out.println(f1.isFile());
byte jj[]=new byte[1024];
while((u=get.read(jj,0,1024))!=-1)
{
fs.write(jj,0,u);
}
fs.close();
System.out.println("File received");
System.out.println("———————————————————————————————");
sock.close();
}catch(Exception e)
{
System.out.println("File not found");
System.out.println("———————————————————————————————");
e.printStackTrace();
System.exit(0);
}
//*** close this socket connection
//sock.close();
}
}
Basically you need to implement a protocol.
Client asks server: do you have file X?
a) Servers says: yes, I got xyz bytes for you, and the md5sum is zyx
Then your client asks for the file; and it can verify it got the correct amount of bytes and that no transmission errors happened. (of course you don't need that verification part; but depending on your context, those are things that you should consider to have in place, too)
b) Server says: no, I don't have that file
Then your client gives an error message to its user.
In other words: the server just reading files and pushing bytes out will not do!
You want to turn your server into something that offers services. And a service has a contract, such as "input" and "output". And services need ways to "negotiate" what should happen next. In your current solution, everything that happen is hardcoded - meaning there is already a protocol in place, but that protocol is defined by the instructions that you put into your code!
I'm trying to make a little chat system. I have a console and a client. Right now only the client need to send messages to the console. I can connect successfully to the server, and i can send one message from client to console. The trouble begins after sending the first message. When the first message i can't send any other messages.
I don't know if it's the console that won't read the message or the client that won't send the message. In this case how could i troubleshoot this?
public class ClientMainClass {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
Scanner scanner = new Scanner(System.in);
System.out.println("Skriv dit username:");
String name = scanner.nextLine();
System.out.println("Du er logget ind som: " + name);
String input;
do{
input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
System.out.println("Du forlod serveren");
socket.close();
continue;
}else {
/*OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);*/
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
Date date = new Date();
String time = date.getDate()+"/"+date.getMonth()+":"+date.getHours()+":"+date.getMinutes();
//Send the message to the server
String message = time+ " - " + name + ": "+input;
printWriter.println(message);
System.out.println(message);
continue;
}
}while (!(input.equals("exit")));
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
My server:
public class Main{
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(br.readLine());
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e){}
}
}
}
To be clear. I can connect to the server. I can send one message from client to console, but no more than one message.
You never read a second line. Your Server accepts a connection, reads one line from that connection and then waits for a new connection, discarding everything that might arrive at the first connection.
Your client however sends all input using the first (and only) connection, which is absolutely correct.
This specific problem can be solved like this:
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while(true){
System.out.println(br.readLine());
}
}
This will cause your program to print everything arriving on that first connection, but it will never accept a second connection.
In order to handle multiple clients, you need a Thread to deal with each one.
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
In this code I use multiple times of retrieve input-output data from two nodes. ... when I use more than two times input output stream it generated this type of error while running this code I need different input and output and that I want to store but unfortunate if I used more than three-time input/output stream it show error
public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to
client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}
public class client {
private static Socket socket;
//public void connect() throws UnknownHostException, IOException{
//}
public void first() throws IOException{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
String sendMessage1="3333";
bw.write(sendMessage1);
bw.flush();
//second();
}
public void second1() throws IOException{
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr;
isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
socket.close();
}
public static void main (String argd[]) throws IOException{
client obj1 = new client();
obj1.first();
}
-----------------------------------------
error
Message received from client is 2
Message sent to the client is Second
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
InputStream and OutputStream are intended to work with a single source and destination. Once you obtain an InputStream that reads from file/socket/whatever source you can use it for multiple consecutive reads. But once you are done reading from that source you need to invoke close() method on your stream.
Not closing your stream is classic reason for a memory leak in Java. In fact for that reason you ALWAYS expected to surround the usage of your source with try catch and always invoke close() method in finally statement. So to insure that it is always invoked. Further more, since close() method itself can cause an Exception, within final statement you need to surround it with its own try-catch. Starting from java 7 there is a new feature called "try with resources" that deals with this particular issue.
Please read about it here
I am writing a Client application which sends requests to the server. I have started my server from Windows, using StartServer batch file. Now, the requests that server expects are HTTP requests. If I open up a request from my web browser, the server sees it and responds to it, but I am having a bad time trying to send the requests from Java.
For example, command "http://localhost/?command=reg&person=sophie" works fine when started from a browser, but from Java it returns a FileNotFound exception.
Here is the code:
public class Client {
private Socket clientSocket;
private final int PORT_NUMBER;
private final String HOST_NAME;
private PrintWriter writer;
private BufferedReader reader;
public Client(int PORT_NUMBER, String HOST_NAME){
this.PORT_NUMBER = PORT_NUMBER;
this.HOST_NAME = HOST_NAME;
try {
clientSocket = new Socket(HOST_NAME, PORT_NUMBER);
writer = new PrintWriter(clientSocket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("Error creating socket!");
}
}
public void registerPerson(String personName) throws IOException{
URL url = new URL("http://localhost/?command=reg&person=sophie");
InputStream in = new BufferedInputStream(url.openStream());
Scanner sc = new Scanner(in);
sc.nextLine();
}
This line, InputStream in = new BufferedInputStream(url.openStream());, returns a FileNotFound exception. Any suggestions on that?
Have you tried using 127.0.0.1 instead of localhost. The problem might arise because java does not recognize your loopback address (ie localhost).
Have you tried accessing the URL differently?
URL fileURL = new URL("http://localhost/?command=reg&person=sophie");
URLConnection connection = fileURL.openConnection();
connection.connect();
inputStream = new java.io.BufferedInputStream(connection.getInputStream());
Also using the IP address instead of localhost is a good idea, as suggested in an another answer.