String data from a Scanner through a PrintWriter - java

I am trying to pass data from a String into a PrintWriter while simultaneously reading from a BufferedReader between two classes named Server.java and Client.java. My problem is that I am having trouble handling the exceptions that are being thrown from the block of code that reads data from the Scanner object (marked below).
Client.java
package root;
/**
* #author Noah Teshima
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private Socket clientSocket;
private BufferedReader bufferedReader;
private InputStreamReader inputStreamReader;
private PrintWriter printWriter;
private Scanner scanner;
public static void main(String[] args) {
new Client("localhost", 1025);
}
public Client(String hostName, int portNumber) {
try {
this.clientSocket = new Socket(hostName, portNumber);
this.bufferedReader = new BufferedReader(this.inputStreamReader = new InputStreamReader(this.clientSocket.getInputStream()));
this.printWriter = new PrintWriter(clientSocket.getOutputStream());
String msg = "",
msg2 = "";
this.printWriter.println(this.getClass());
this.printWriter.flush();
System.out.println(this.getClass().getName() + " is connected to " + this.bufferedReader.readLine());
while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
this.printWriter.println(this.getClass().getName() + ": " + msg);
this.printWriter.flush();
while((msg2 = this.bufferedReader.readLine()) != null) {
System.out.println(msg2);
}
}
this.clientSocket.close();
}catch(IOException exception) {
exception.printStackTrace();
}
}
}
Stack trace::
Exception in thread "main" java.lang.NullPointerException
at root.Client.<init>(Client.java:47)
at root.Client.main(Client.java:25)
The code used to read from the BufferedReader and write to a PrintWriter is the same for both classes, so I only posted Client.java. If anyone would like to see the other class file, I would be happy to do so.

Before you use
while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
You should have initialized the scanner.
The scanner object is null when you used it, and hence the NullPointerException.
I do not see a scanner = new Scanner(...); anywhere within your code,
maybe you have forgetten about it?

Related

Pass an Object from a javaFX application to the Controller to have multiple threads with the controller

I built myself a small multithread Server and have to run it over different ports on my local Host.
Basically I start the Application over "AddMovieApplication", "AddMovieManually" is the Controller here. I Start my Server and my Client, which connects to the server on a onetime port for a stable connection. I somehow need to tell the controller now over which Socket it has to send the data for every new client. Is there a way to pass the client to the controller so that the Application knows the socket?
Controller
package com.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.model.Movie;
import com.model.MyClient;
import com.view.AddMovieApplication;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import com.controller.SceneController;
public class AddMovieManually extends SceneController{
MyClient client = new MyClient();
#FXML
public TextField textTitle;
#FXML
public TextField textGenre;
#FXML
public TextField textPosterSrc;
#FXML
public TextField textReleaseDate;
#FXML
public TextField textMovieLength;
#FXML
public TextField textRegisseur;
#FXML
public TextField textAuthor;
#FXML
public TextField textCast;
ArrayList<String> genreList = new ArrayList<>();
ArrayList<String> authorList = new ArrayList<>();
ArrayList<String> castList = new ArrayList<>();
public AddMovieManually() throws IOException {
}
#FXML
public void genreAdd(){
genreList.add(textGenre.getText());
textGenre.clear();
}
#FXML
public void authorAdd(){
authorList.add(textAuthor.getText());
textAuthor.clear();
}
#FXML
public void castAdd(){
castList.add(textCast.getText());
textCast.clear();
}
#FXML
//Checks if the Film already exists, if not, create a new movie Object using the Parameter
//given from the Textfields and pushes it into the Database. If it already exists take the
//Movie Object off the database, change the variables and pushes it back in.
public boolean save() {
String title = textTitle.getText();
String posterSrc = textPosterSrc.getText();
int releaseDate = Integer.parseInt(textReleaseDate.getText());
int movieLength = Integer.parseInt(textMovieLength.getText());
String regisseur = textRegisseur.getText();
ArrayList<String> genre = this.genreList;
ArrayList<String> author = this.authorList;
ArrayList<String> cast = this.castList;
Movie movie = new Movie(title,posterSrc,releaseDate,movieLength,regisseur,genreList,authorList,castList);
System.out.println(movie.toString());
try {
String jsonMovie = new ObjectMapper().writeValueAsString(movie);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(this.client.getClientSocket().getOutputStream()));
pw.println(jsonMovie);
pw.flush();
pw.close();
}catch(Exception e){
System.out.println("Sending Movie to Server failed ...");
return false;
}
return true;
}
#FXML
//Goes back to the last page without doing anything
public void abort(){
switchToSceneWithStage("Login.fxml");
}
}
Application
public class AddMovieApplication extends Application {
public void start(Stage stage) throws Exception {
Scene newScene = new Scene(FXMLLoader.load(getClass().getResource("/addFilmGUI.fxml")));
//FXMLLoader fxmlLoader = new FXMLLoader(addMovieApplication.class.getResource("addFilmGUI.fxml"));
//Scene scene = new Scene(fxmlLoader.load());
stage.setTitle("Here you can manually put in movies");
stage.setScene(newScene);
stage.show();
}
public static void main() {launch();}
}
The Client I want to start the Application when it connects
package com.model;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import com.controller.AddMovieManually;
import com.view.AddMovieApplication;
import com.view.MainAppGUI;
public class MyClient {
public MyClient() throws IOException {
/* for the Login we create a client which requests a connection over port 4 and gets a new
port for usage from the Server afterwards since we don't have a switch for our Project.*/
Socket requestSocket = new Socket("localhost", 4999);
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(requestSocket.getInputStream())));
int portForConnection = scanner.nextInt();
System.out.println("Connected to Server over port : " + portForConnection);
scanner.close();
this.clientSocket = new Socket("localhost", portForConnection);
this.printwriter = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(clientSocket.getOutputStream())));
this.scanner = new Scanner(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
}
private Socket clientSocket = null;
final PrintWriter printwriter;
final Scanner scanner;
private User user;
public Socket getClientSocket() { return this.clientSocket; }
public User getUser() { return this.user; }
public void setUser(User user) { this.user = user; }
public static void main(String[] args) throws IOException {
MyClient client = new MyClient();
AddMovieApplication.main();
//AddMovieManually add = new AddMovieManually(client.getClientSocket());
}
}
I also give you the code for the Server just in case
package com.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class myServer {
public static void main(String[] args) throws IOException {
int requestPort = 4999;
int newClientPort = 5001;
while (true) {
ServerSocket serverSocket = new ServerSocket(requestPort);
/*Create a temporary connection on our request port 10 to send
a port for stable connection to every Client */
System.out.println("Waiting for Client ...");
Socket clientSocketTemp = serverSocket.accept();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(clientSocketTemp.getOutputStream()));
pw.println(newClientPort);
pw.flush();
serverSocket.close();
ServerSocket stableConnectedServerSocket = new ServerSocket(newClientPort);
Socket stableConnectionSocket = stableConnectedServerSocket.accept();
pw.close();
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("[Server] : waiting for input ...");
while(stableConnectionSocket.isConnected()) {
try {
ObjectMapper om = new ObjectMapper();
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(stableConnectionSocket.getInputStream())));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(stableConnectionSocket.getOutputStream()));
if (scanner.hasNextLine()) {
String inputString = scanner.nextLine();
System.out.println(inputString);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("create Streams failed");
throw new RuntimeException(e);
}
}
}
}).start();
newClientPort++;
}
}
public static void sendJsonToClient(Scanner input ,PrintWriter output,String userJson){
output.println(userJson);
output.flush();
}
public static void sendJsonToDatabase(String userJson, int databasePort) throws IOException {
Socket databaseSocket = new Socket("localhost",databasePort);
PrintWriter output = new PrintWriter(new OutputStreamWriter(databaseSocket.getOutputStream()));
output.println(userJson);
output.flush();
output.close();
}
}

Need help on Pi Calculation with single multiServer - (N)Clients programm on Java. (Sockets)

I am trying to make a single mutlithreaded Server , that many clients can connect. Every client takes his iD and a number of steps and tries to calculate Pi =3,14 with accuracy, after that every client sends its result back to Server and the Server Calculates the Final result finnaly prints Pi.
(Every Client works at the same time).
(We know from start how many Clients will connect)
So far I created the main Server , the ServerThread , and a ServerProtocol where every action is written there. A loop helps that many clients can connect. I gave as a string the specific number of client and the numSteps it has to calculate pi.
On the client side, I made the main Client and the ClientProtocol with the actions. So , the client take the string, make it integer and start calculating pi. At the end sends the result as a string and the Server makes it Integer and put it on an Array to calculate and print 3.14 .
So i am somewhere lost and can't find where , so any help will be aprecciated.
Server
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ServerTCP {
private static final int PORT = 1234;
public static String num;
public static Lock lock = new ReentrantLock();
public static int clientsSoFar=-1;
public static void main(String[] args) throws IOException {
// server is listening on port
ServerSocket connectionSocket = new ServerSocket(PORT);
System.out.println("Server is listening to port: " + PORT);
// running infinite loop for getting client request
while(true) {
//Wait for connection and produce actual socket
Socket dataSocket = null;
// socket object to receive incoming client requests
dataSocket=connectionSocket.accept();
clientsSoFar++;
System.out.println("Received request from " + dataSocket.getInetAddress());
//Server Thread
ServerTCPThread sthread = new ServerTCPThread(dataSocket);
sthread.start();
}
}
}
ServerThread
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;
public class ServerTCPThread extends Thread{
public static int clientsSoFar;
private Socket dataSocket;
private InputStream is;
private BufferedReader in;
private OutputStream os;
private PrintWriter out;
private static final String EXIT = "!";
public ServerTCPThread(Socket socket)
{
dataSocket = socket;
try {
is = dataSocket.getInputStream();
in = new BufferedReader(new InputStreamReader(is));
os = dataSocket.getOutputStream();
out = new PrintWriter(os,true);
}
catch(IOException e) {
System.out.println("I/O Error " + e);
}
}
public void run() {
int clientsP =2;
int numSteps=100;
String p = "2 100";
String inmsg, outmsg;
try {
//epeksergasia
String num1 = String.valueOf(ServerTCP.clientsSoFar);
String num2 = String.valueOf(numSteps/clientsP);
ServerTCP.num =num1+" "+num2;
//epeksergasia
int numClient;
String[] splited = p.split("\\s+");
numClient=Integer.parseInt(splited[0]);
ServerTcpProtocol app = new ServerTcpProtocol();
outmsg = app.message();
out.println(outmsg);
inmsg = in.readLine();
outmsg = app.processRequest(inmsg);
// while(!EXIT.equals(inmsg)) {
// outmsg = app.processRequest(inmsg);
//out.println(outmsg);
//inmsg = in.readLine();
// }
double outMsgDouble = Double.parseDouble(outmsg);
double [] pin = new double[clientsP];
Arrays.fill(pin, 0);
ServerTCP.lock.lock();
for (int i=0; i<clientsP; i++)
if (pin[i]==0)
pin[i]=outMsgDouble;
ServerTCP.lock.unlock();
dataSocket.close();
}
catch (IOException e) {
System.out.println("I/O Error --> " + e);
}
}
}
ServerProtocol
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ServerTcpProtocol {
public String processRequest(String theInput) {
System.out.println("Received message from client: " + theInput);
String theOutput = theInput;
//System.out.println("Send message to client: " + theOutput);
return theOutput;
}
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
public String message() throws IOException {
System.out.println("Send number to Client: "+ ServerTCP.num);
//String theOutput = user.readLine();
String theOutput=ServerTCP.num;
//SimpleServerTCP.p="+1";
return theOutput;
}
}
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ClientTCP {
//Client should know servers address/name
private static final String HOST = "localhost";
private static final int PORT = 1234;
private static final String EXIT = "!";
public static double sum;
public static Lock lock = new ReentrantLock();
public static void main(String[] args) throws IOException {
//Try to connect to server
Socket dataSocket = new Socket(HOST, PORT);
//Set up input and output streams
InputStream is = dataSocket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
OutputStream os = dataSocket.getOutputStream();
PrintWriter out = new PrintWriter(os, true);
System.out.println("Connection to " + HOST + " established.");
//Send request and then receive and process reply
String inmsg, outmsg;
ClientTcpProtocol app = new ClientTcpProtocol();
inmsg = in.readLine();
System.out.println("Time to send back to Server");
outmsg = app.answere(inmsg);
out.println(outmsg);
//Socket close
dataSocket.close();
System.out.println("Data Socket closed.");
}
}
ClientProtocol
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ClientTcpProtocol {
BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
//Request comes from user input
public String prepareRequest() throws IOException {
System.out.print("Enter message to send to server:");
String theOutput = user.readLine();
return theOutput;
}
//Reply goes to user screen
public void processReply(String theInput) throws IOException {
System.out.println("Message received from server: " + theInput);
}
public String answere(String theInput) {
System.out.println("Received message from Server: " + theInput);
//String theOutput = theInput;
int myId;
double result=0;
int myStart=1;
int myStop;
int numStep;
double table= 0;
int numStep0;
int numStep1;
int numStep2;
int numStep3;
int numStep4;
//Input split
String[] splited = theInput.split("\\s+");
myId = Integer.parseInt(splited[0]);
numStep=Integer.parseInt(splited[1]);
myStop=numStep;
double step = 1.0 / (double)numStep;
ClientTCP.lock.lock();
try {
for(int i = myStart; i < myStop; i++) {
double x = ((double)i+0.5)*step;
table += 4.0/(1.0+x*x);
}
//Maybe this oart should be at the end of Server before calculation???
result = result + ( table * step);
String theOutput = Double.toString(result);
System.out.println("Send p to Server:" + theOutput);
return theOutput;
}finally {
ClientTCP.lock.unlock();
}
}
}

objectInputStream.readObject() throws exception java.io.OptionalDataException

Can someone please resolve this issue.
Using JDK 1.8, I am trying to build a very simple chat application in Java using Sockets. In my client class as soon as following line executes
Message returnMessage = (Message) objectInputStream.readObject();
it throws exception.
Exception in thread "main" java.io.OptionalDataException
I am writing only objects of type Message to the stream and reading objects of type Message, since i wrote once, i dont think i am doing anything wrong in reading them in sequence.
Q. Also please let me know what is the best way to debug this type of application, how to hit the breakpoint in server while running client ?
Client
package com.company;
import sun.misc.SharedSecrets;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException{
Socket socket = new Socket("localhost", Server.PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String readerInput = bufferedReader.readLine();
String[] readerInputTokens = readerInput.split("\u0020");
if(readerInputTokens.length != 2) {
System.out.println("Usage: Client <integer> <integer>");
} else {
Integer firstNumber = Integer.decode(readerInputTokens[0]);
Integer secondNumber = Integer.decode(readerInputTokens[1]);
Message message = new Message(firstNumber, secondNumber);
objectOutputStream.writeObject(message);
System.out.println("Reading Object .... ");
Message returnMessage = (Message) objectInputStream.readObject();
System.out.println(returnMessage.getResult());
socket.close();
}
}
public static boolean isInteger(String value) {
boolean returnValue = true;
try{Integer.parseInt(value);}
catch (Exception ex){ returnValue = false; }
return returnValue;
}
}
Server
package com.company;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public final static int PORT = 4446;
public static void main(String[] args) throws IOException, ClassNotFoundException {
new Server().runServer();
}
public void runServer() throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up & ready for connections ...");
// This while loop is necessary to make this server able to continuously in listning mode
// So that whenever a client tries to connect, it let it connect.
while (true){
Socket socket = serverSocket.accept(); // Server is ready to accept connectiosn;.
// Initialize Server Thread.
new ServerThread(socket).start();
}
}
}
Sever Thread
package com.company;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket socket = null;
ServerThread(Socket socket){
this.socket = socket;
}
public void run() {
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeChars("\n");
objectOutputStream.flush();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
Message message = (Message) objectInputStream.readObject();
multiplyNumbers(message);
System.out.println("Writing: "+message.toString());
objectOutputStream.writeObject(message);
System.out.println("Message Written");
socket.close();
} catch( IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
private void multiplyNumbers(Message message) {
message.setResult(message.getFirstNumber().intValue() * message.getSecondNumber().intValue());
}
}
Message Class
package com.company;
import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = -72233630512719664L;
Integer firstNumber = null;
Integer secondNumber = null;
Integer result = null;
public Message(Integer firstNumber, Integer secondNumber) {
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
public Integer getFirstNumber() {
return this.firstNumber;
}
public Integer getSecondNumber() {
return this.secondNumber;
}
public Integer getResult() {
return this.result;
}
public void setResult(Integer result) {
this.result = result;
}
#Override
public String toString() {
return "Message{" +
"firstNumber=" + firstNumber +
", secondNumber=" + secondNumber +
", result=" + result +
'}';
}
}
objectOutputStream.writeChars("\n");
Why are you writing a newline to an ObjectOutputStream? You're never reading it. Don't do that. Remove this wherever encountered.

Connect multiple clients to one server

I'm trying to connect all my clients to one server. I've done some research and found out that the easiest way to do it is create a new thread for every client that connects to the server. But I am already stuck on the part where a client disconnects and reconnect.
Client
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test {
private static int port = 40021;
private static String ip = "localhost";
public static void main(String[] args) throws UnknownHostException,
IOException {
String command, temp;
Scanner scanner = new Scanner(System.in);
Socket s = new Socket(ip, port);
while (true) {
Scanner scanneri = new Scanner(s.getInputStream());
System.out.println("Enter any command");
command = scanner.nextLine();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(command);
temp = scanneri.nextLine();
System.out.println(temp);
}
}
}
Server
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
String command, temp;
ServerSocket s1 = new ServerSocket(40021);
while (true) {
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine()) {
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
}
}
}
When I connect once it works correctly but as soon as I disconnect the client and try to reconnect (or connect a second client) it does not give an error or anything it just does not function. I am trying to keep it as basic as possible.
The output with one client:
When I try and connect a second client:
I hope someone could help me out. Thanks in advance.
Your server currently handles only 1 client at a time, use threads for each client, Modify your server code like this:-
public static void main(String[] args) throws IOException
{
ServerSocket s1 = new ServerSocket(40021);
while (true)
{
ss = s1.accept();
Thread t = new Thread()
{
public void run()
{
try
{
String command, temp;
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine())
{
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
};
t.start();
}
}

How to create a simple Server Client Application Using RUDP in Java?

I was working on a simple application to transfer files between two machines using UDP, but that turned out to be lossy and unreliable, so while searching the Internet I found this project named Simple Reliable UDP here, but they don't have any documentation or any example code. So if there is any who can help me with this code I will be grateful because I'm newbie in Java. I started with writing simple server client app, but I got address already bind exception. To make clear I want to use UDP connections only that's why I'm trying to implement ReliableServerSocket and ReliableSocket.
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class udpServer implements Runnable{
ReliableServerSocket rss;
///ocket rs;
ReliableSocket rs;
public udpServer() throws IOException {
rss= new ReliableServerSocket(9876);
}
public void run(){
while (true){
try {
rs=(ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println(""+rs.getInetAddress());
BufferedReader inReader = new BufferedReader (new InputStreamReader (rs.getInputStream()));
//BufferedWriter outReader = new BufferedWriter (new OutputStreamWriter (rs.getOutputStream()));
String str= ""+inReader.readLine();
if(str.contains("UPLOAD")){
System.out.println("Client wants to upload file");
}else if(str.contains("D1")){
System.out.println("Client wants to download file");
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) throws Exception
{
System.out.println("UDP Server Executed");
Thread t= new Thread( new udpServer());
t.start();
}
}
Client Code here
package stackoverflow;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UdpFileClient {
BufferedWriter outReader;
ReliableSocket server;
public UdpFileClient(boolean b1, boolean b2) throws IOException {
if (b1) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("D1");
System.out.println("Download Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
if (b2) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("UPLOAD");
System.out.println("Upload Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
}
public static void main(String args[]) throws Exception {
System.out.println("UDP CLient Executed");
new UdpFileClient(true, true);
}
}
I already know I can use TCP/IP, but it is kind of requirement for the project to use UDP. If any other way to send files in lossless way using UDP with good speed will also be helpful.
Thanks in advance!!
I tried RUDP and found that i was not printing my output, i know this is a silly mistake.
UDP Client
package UDPClient;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtestc {
ReliableSocket server;
public UDPtestc() throws IOException {
server = new ReliableSocket();
server.connect(new InetSocketAddress("127.0.0.1", 9876));
byte[] buffer = new byte[1024];
int count,progress=0;
InputStream in = server.getInputStream();
while((count=in.read(buffer)) >0){
progress+=count;
System.out.println(""+progress);
}
server.close();
}
public static void main(String[] args) throws IOException {
new UDPtestc();
}
}
UDPserver
package UDPServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtests implements Runnable {
ReliableServerSocket rss;
ReliableSocket rs;
String file;
FileInputStream bin;
public UDPtests() throws IOException {
rss = new ReliableServerSocket(9876);
Thread serverthread = new Thread(this);
serverthread.start();
}
public void run() {
while (true) {
try {
rs = (ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println("" + rs.getRemoteSocketAddress());
file = "";
Long size=0L;
file += "10MB.txt";
size+=10*1024*1024;
RandomAccessFile r1= new RandomAccessFile(file,"rw");
r1.setLength(size);
byte[] sendData = new byte[1024];
OutputStream os = rs.getOutputStream();
//FileOutputStream wr = new FileOutputStream(new File(file));
bin= new FileInputStream(file);
int bytesReceived = 0;
int progress = 0;
while ((bytesReceived = bin.read(sendData)) > 0) {
/* Write to the file */
os.write(sendData, 0, bytesReceived);
progress += bytesReceived;
System.out.println(""+progress);
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws IOException {
new UDPtests();
}
}
Soon i will post other tuts on RUDP if it will be possible.

Categories

Resources