Currently working on making a pipeline among two files in java and I would to transmit a float via stream bytes. However I don't know how I can receive it and convert it into a float. Here is what I have done so far:
(3 files)
Consumi.java:
package tryout5_stream_bytes;
import java.io.Serializable;
public class Consumi implements Serializable{
private float consumi = 0.0F;
public Consumi(float consumi){
this.consumi = consumi;
}
public float getConsumi(){
return consumi;
}
public byte[] getBytes(String encode){
return String.valueOf(consumi).getBytes();
}
}
SimulaConsumi.java
package tryout5_stream_bytes;
import java.io.PipedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicBoolean;
public class SimulaConsumi implements Runnable {
private AtomicBoolean isRunning = new AtomicBoolean(false);
private PipedOutputStream pos = null;
public SimulaConsumi(PipedOutputStream pos){
this.pos = pos;
}
#Override
public void run(){
isRunning.set(true);
while(isRunning.get()){
Consumi c = new Consumi((float) (30 * Math.random()));
byte[] message = null;
message = c.getBytes("UTF-8");
try{
pos.write(message);
pos.flush();
} catch(IOException e){
e.printStackTrace();
}
try{
Thread.sleep(1000);
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void terminaSimulaConsumi(){
isRunning.set(false);
}
}
Main.java
package tryout5_stream_bytes;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.io.*;
import java.lang.object;
import java.nio.ByteBuffer;
public class Main {
public static void main(String[] args){
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = null;
try{
pos = new PipedOutputStream(pis);
}catch(IOException e){
e.printStackTrace();
}
SimulaConsumi sc = new SimulaConsumi(pos);
Thread tsc = new Thread();
tsc.start();
while(true){
try{
Thread.sleep(900);
}catch(InterruptedException e){
e.printStackTrace();
}
byte[] buffer = new byte[256];
try{
pis.read(buffer);
}catch(IOException e){
e.printStackTrace();
}
float received = //Get a float from a stream bytes???
System.out.println("Value:"+received);
}
}
}
I believe that the sending of the float in the file "SimulaConsumi" is done well (however I might still be wrong). On the other hand I really have no idea how I can receive it!
Related
I am creating a Web App in which, I have to upload files by splitting them using parallel processing and multi threading and while downloading I have to combine them back to a single file using multi threading and parallel processing.
I want to combine split files into a single. But its not working as I expected to work.
The number of threads created is equal to the number of parts the file have been split.
And the threads should run parallelly and should run only once. But the threads are called several times. Help me fix the code.
UploadServlet.java
import java.util.Arrays;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.apache.commons.io.IOUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import jakarta.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 100L;
public static String fileName;
public static long size;
public static int noOfParts;
public static String type;
public static byte[] b;
private static final String INSERT_USERS_SQL = "INSERT INTO uploadlist" +
" (filename, filesize, noofparts) VALUES " +
"(?, ?, ?);";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part file = request.getPart("file");
fileName=file.getSubmittedFileName();
type=file.getContentType();
PrintWriter writer=response.getWriter();
file.write(fileName);
String n = request.getParameter("parts");
size = file.getSize();
Integer temp1 = Integer.parseInt(n);
noOfParts = temp1.intValue();
set();
writer.println("File Uploaded Successfully");
file.delete();
}
public static void set()
{
Split.split(fileName,size,noOfParts);
try {
Connection c = DataBaseConnection.getConnection();
PreparedStatement preparedStatement = c.prepareStatement(INSERT_USERS_SQL);
preparedStatement.setString(1, fileName);
preparedStatement.setLong(2, size);
preparedStatement.setInt(3, noOfParts);
System.out.println(preparedStatement);
preparedStatement.executeUpdate();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
From UploadServlet Split.split() is called to split the files into number of parts.
Split.java
import java.io.*;
import java.util.Arrays;
public class Split implements Runnable
{
int i;
long size;
int noOfParts;
String fileName;
Split()
{
fileName="";
}
Split(String fileName, int i, long size, int noOfParts)
{
this.fileName=fileName;
this.i=i;
this.size=size;
this.noOfParts=noOfParts;
}
public void run()
{
try
{
System.out.println(i);
RandomAccessFile in = new RandomAccessFile("D:\\temp\\"+fileName,"r");
int bytesPerSplit = (int)(size/noOfParts);
int remainingBytes = (int)(size % noOfParts);
byte[] b;
if(i!=noOfParts-1)
{
b = new byte[bytesPerSplit];
}
else
{
b = new byte[bytesPerSplit+remainingBytes];
}
in.seek((long)i*bytesPerSplit);
in.read(b);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\Upload\\"+fileName+i+".bin"));
for(byte temp : b)
out.write(temp);
out.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void split(String fileName, long size, int noOfParts)
{
for(int i=0; i<noOfParts; i++)
{
Split obj = new Split(fileName,i,size,noOfParts);
Thread t = new Thread(obj);
t.start();
}
}
}
In this program, I split the files according to number of parts. And I want to combine them back using Parallel Processing and Multi Threading.
DownloadServlet.java\
import jakarta.servlet.http.HttpServlet;
import org.postgresql.Driver;
import java.sql.Statement;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.util.Arrays;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String name = new String(request.getParameter("fileName"));
int noOfParts = Integer.parseInt(request.getParameter("parts"));
int size = Integer.parseInt(request.getParameter("size"));
File downloadFile = new File("D:\\Download\\"+name);
Combine.combine(name,noOfParts,size);
int length = (int)downloadFile.length();
String completeFile=name;
ServletContext context=getServletContext();
String mimeType = context.getMimeType(completeFile);
if (mimeType == null)
{
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setContentLength((int)length);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", completeFile);
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
byte[] buffer = new byte[(int)length];
while ((in != null) && ((length = in.read(buffer)) != -1))
{
outStream.write(buffer,0,length);
}
if ((length = in.read(buffer))== -1) {
outStream.write(buffer, 0, length);
}
Arrays.fill(buffer, (byte)0);
in.close();
outStream.flush();
outStream.close();
}
}
From DownloadServlet, Combine.combine() is called to combine the split parts into a single file.
Combine.java
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.*;
import java.util.Scanner;
import java.util.Arrays;
public class Combine implements Runnable
{
String name;
int size;
int noOfParts;
int i;
public static String root = "D:\\Upload\\";
Combine(String name,int noOfParts,int size, int i)
{
this.name = name;
this.noOfParts=noOfParts;
this.size=size;
this.i=i;
}
public void run()
{
try
{
System.out.println(i);
RandomAccessFile out = new RandomAccessFile("D:\\Download\\"+name,"rw");
int bytesPerSplit = size/noOfParts;
int remainingBytes = size%noOfParts;
String temp=name+i+".bin";
RandomAccessFile file = new RandomAccessFile(root+temp,"r");
long l=file.length();
byte[] b = new byte[(int)l];
file.read(b);
out.seek(i*bytesPerSplit);
out.write(b);
file.close();
out.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void combine(String name, int noOfParts, int size)
{
for(int i=0; i<noOfParts; i++)
{
Combine obj = new Combine(name,noOfParts,size,i);
Thread t = new Thread(obj,"Thread"+i);
t.start();
}
}
}
I have attached the image in which the numbers represent the part of the file being read and combined using threads.
The output shows that the threads keeping on executing again and again.
I don't know where is the error or any logical mistake in my program.
Help me solve this problem.
I am developing a web server(experimenting with network programming in java) using Java SE only, everything seems to be working well (i.e HTML and CSS files) but the problem is with images, they are written to browser as bytes with the correct mime type and the correct size but the problem is that they wont display on the web browser, its showing a black Screen, developers tool on Google Chrome shows the image has been properly downloaded with a status code of 200 OK and the correct file size . Below is my code.
package miniserver;
import java.io.*;
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
enum status_code{
OK(200),NOT_FOUND(404),FORBIDDEN(403);
private int code;
status_code(int code){
this.code=code;
}
public int getCode(){
return this.code;
}
}
public class MiniServer {
public static void main(String[] args) {
try{
InetAddress address = InetAddress.getLocalHost();
try{
ServerSocket webserver = new ServerSocket(1521);
System.out.println("Web Sever Started");
System.out.println("Running On " + address.getHostAddress());
Date k= new Date();
System.out.println(k.toString());
Socket browser ;
while(true){
browser=webserver.accept();
requestHandler handle = new requestHandler(browser);
}
}catch(IOException err){
System.out.println("Server Already Running"+err.getMessage());
}
}catch(UnknownHostException ex){
Logger.getLogger(MiniServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class requestHandler implements Runnable{
static int nRequest=0;
private Socket client;
private BufferedOutputStream stream;
FileOutputStream out;
BufferedOutputStream response;
BufferedReader request;
requestHandler(Socket client){
try{
this.client=client;
this.response=new BufferedOutputStream (client.getOutputStream());
this.request=new BufferedReader( new InputStreamReader(client.getInputStream()));
new Thread(this).start();
}catch(IOException e){
}
}
#Override
public void run(){
try{
Scanner header = new Scanner(this.request);
String rf="";
String firstline=null;
try{
firstline=header.nextLine();
rf =firstline.split("\\s")[1].split("\\?")[0];
System.out.println(rf);
}catch(NoSuchElementException err){
System.out.println("NO HEADERS FOUND"+err.getMessage());
}
fileInputStream page;
fileInputStream errorpage=new fileInputStream("web/index.html");
status_code code=null;
String type="";
if(firstline.startsWith(".5.")){
page=errorpage;
code=status_code.FORBIDDEN;
}else if(rf.equals("/")){
this.out = new FileOutputStream("test/index.html");
type="text/html";
page = new fileInputStream("web/index.html");
code=status_code.OK;
}else{
this.out = new FileOutputStream("test"+rf);
type = mime("web"+rf);
File local = new File("web"+rf);
if(local.exists()){
page=new fileInputStream(local);
code=status_code.OK;
}
else{
page=errorpage;
code=status_code.NOT_FOUND;
}
}
reply(code,page,type);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
void reply(status_code c,fileInputStream file,String type) throws IOException{
StringBuilder head = new StringBuilder();
head.append("HTTP/1.1 "+c.getCode()+" "+c+"\r\n");
head.append("Date: "+ new Date().toString()+"\r\n");
head.append("Server: Kilobyte MiniServer\r\n");
head.append("Connection: close\r\n");
head.append("Content-Type: "+type+" \r\n");
head.append("Content-length: "+file.available()+"\n\r");
head.append("\n\r");
int length=head.length();
for(byte b: head.toString().getBytes()){
this.response.write(b);
}
int pageBytes;
try{
while((pageBytes=file.read()) != -1){
this.response.write(pageBytes);
this.out.write(pageBytes);
}
file.close();
this.response.close();
this.request.close();
}catch(IOException e){
}
}
synchronized int incr(){
this.notifyAll();
return ++nRequest;
}
String mime(String file){
if(file.endsWith("css"))
return "text/css";
else if(file.endsWith("html"))
return "text/html";
else if(file.endsWith("js"))
return "text/javascript";
else if(file.endsWith("JPG"))
return "image/jpg";
else if(file.endsWith("jpg"))
return "image/jpg";
else if(file.endsWith("jpg"))
return "image/jpg";
else if(file.endsWith("png"))
return "image/png";
return "text";
}
}
class fileInputStream extends FileInputStream{
String f;
fileInputStream(String f) throws FileNotFoundException{
super(f) ;
this.f=f;
}
fileInputStream(File f) throws FileNotFoundException{
super(f);
this.f=f.toString();
}
#Override
public String toString(){
return f;
}
}
as you have seen before I'm working on a download manager in java, I have asked This Question and I have read This Question But These hadn't solve my problem. now I have wrote another code in java. but there is a problem. when download finishes file is larger than it's size and related software can't read it
This is image of my code execution :
as you see file size is about 9.43 MB
This is My project directory's image:
as you see my downloaded filesize is about 13 MB
So what is my Prooblem?
here is my complete source code
Main Class:
package download.manager;
import java.util.Scanner;
/**
*
* #author Behzad
*/
public class DownloadManager {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter url here : ");
String url = input.nextLine();
DownloadInfo information = new DownloadInfo(url);
}
}
DownloadInfo Class:
package download.manager;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DownloadInfo {
private String downloadUrl;
private String fileName;
private String fileExtension;
private URL nonStringUrl;
private HttpURLConnection connection;
private int fileSize;
private int remainingByte;
private RandomAccessFile outputFile;
public DownloadInfo(String downloadUrl) {
this.downloadUrl = downloadUrl;
initiateInformation();
}
private void initiateInformation(){
fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1, downloadUrl.length());
fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());
try {
nonStringUrl = new URL(downloadUrl);
connection = (HttpURLConnection) nonStringUrl.openConnection();
fileSize = ((connection.getContentLength()));
System.out.printf("File Size is : %d \n", fileSize);
System.out.printf("Remain File Size is : %d \n", fileSize % 8);
remainingByte = fileSize % 8;
fileSize /= 8;
outputFile = new RandomAccessFile(fileName, "rw");
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadInfo.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DownloadInfo.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.printf("File Name is : %s\n", fileName);
System.out.printf("File Extension is : %s\n", fileExtension);
System.out.printf("Partition Size is : %d MB\n", fileSize);
int first = 0 , last = fileSize - 1;
ExecutorService thread_pool = Executors.newFixedThreadPool(8);
for(int i=0;i<8;i++){
if(i != 7){
thread_pool.submit(new Downloader(nonStringUrl, first, last, (i+1), outputFile));
}
else{
thread_pool.submit(new Downloader(nonStringUrl, first, last + remainingByte, (i+1), outputFile));
}
first = last + 1;
last += fileSize;
}
thread_pool.shutdown();
try {
thread_pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(DownloadInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and this is my downloader class:
package download.manager;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Behzad
*/
public class Downloader implements Runnable{
private URL downloadURL;
private int startByte;
private int endByte;
private int threadNum;
private RandomAccessFile outputFile;
private InputStream stream;
public Downloader(URL downloadURL,int startByte, int endByte, int threadNum, RandomAccessFile outputFile) {
this.downloadURL = downloadURL;
this.startByte = startByte;
this.endByte = endByte;
this.threadNum = threadNum;
this.outputFile = outputFile;
}
#Override
public void run() {
download();
}
private void download(){
try {
System.out.printf("Thread %d is working...\n" , threadNum);
HttpURLConnection httpURLConnection = (HttpURLConnection) downloadURL.openConnection();
httpURLConnection.setRequestProperty("Range", "bytes="+startByte+"-"+endByte);
httpURLConnection.connect();
outputFile.seek(startByte);
stream = httpURLConnection.getInputStream();
while(true){
int nextByte = stream.read();
if(nextByte == -1){
break;
}
outputFile.write(endByte);
}
} catch (IOException ex) {
Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This file is MP4 for as you seen, but Gom can't play it
Would you please help me?
OoOoOopppps finally I found what is the problem , It's all on seek method. because i have a file and 8 threads. so seek method changes the cursor repeatedly and make larger file and unexecutable file :), But I'm so sorry . I can't show whole code :)
I want to create a server that can accept multiple connections and then bind 2 clients as a pair and forward the data between these 2 clients. But it is about multiple pairs of clients. I already have multithread server that can create a new thread for each new connected client. The problem for me is that these threads dont know of each other and somehow I have to connect 2 clients to a connection pair.
For now I just create these pair connection as this: I wait for the first client, then I wait for the second client and then open a thread for the input of client 1 that gets forwarded to client 2 and the other way around. This is not usable for multiple clients.
How can I do this decent?
The way I see it, a client would need to
establish a TCP(?) connection with your server,
identify itself
give the ID of the other client it wishes to talk to
The first that connects would have to be kept on hold (in some global table in your server) until the second client connects.
Once a pair of clients would have been recognized as interlocutors, you would create a pair of threads to forward the data sent by each client to the other one.
UPDATE: Example
ClientSocket.java
package matchmaker;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientSocket implements Closeable {
private final Socket socket;
private final InputStream in;
private final OutputStream out;
private final String ownId;
private final String peerId;
public ClientSocket(Socket socket) throws IOException {
this.socket = socket;
this.in = socket.getInputStream();
this.out = socket.getOutputStream();
DataInputStream din = new DataInputStream(in);
this.ownId = din.readUTF();
this.peerId = din.readUTF();
}
public ClientSocket(String server, int port, String ownId, String peerId)
throws IOException {
this.socket = new Socket(server, port);
this.socket.setTcpNoDelay(true);
this.in = socket.getInputStream();
this.out = socket.getOutputStream();
this.ownId = ownId;
this.peerId = peerId;
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(ownId);
dout.writeUTF(peerId);
}
public String getOwnId() {
return ownId;
}
public String getPeerId() {
return peerId;
}
public InputStream getInputStream() {
return in;
}
public OutputStream getOutputStream() {
return out;
}
#Override
public void close() throws IOException {
socket.close();
}
}
Matchmaker.java: the server
package matchmaker;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Matchmaker extends Thread {
private static final Logger LOG
= Logger.getLogger(Matchmaker.class.getName());
private final int port;
private final Map<ClientPair,ClientSocket> waiting = new HashMap<>();
public static void main(String[] args) {
try {
int port = 1234;
int st = 0;
for (String arg: args) {
switch (st) {
case 0:
switch (arg) {
case "-p":
st = 1;
break;
default:
System.out.println("Unknown option: " + arg);
return;
}
break;
case 1:
port = Integer.parseInt(arg);
st = 0;
break;
}
}
Matchmaker server = new Matchmaker(port);
server.start();
server.join();
} catch (InterruptedException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
private Matchmaker(int port) {
this.port = port;
setDaemon(true);
}
#Override
public void run() {
try {
ServerSocket server = new ServerSocket(port);
while (true) {
ClientSocket socket = new ClientSocket(server.accept());
ClientPair pair = new ClientPair(
socket.getOwnId(), socket.getPeerId());
ClientSocket other;
synchronized(this) {
other = waiting.remove(pair.opposite());
if (other == null) {
waiting.put(pair, socket);
}
}
if (other != null) {
LOG.log(Level.INFO, "Establishing connection for {0}",
pair);
establishConnection(socket, other);
} else {
LOG.log(Level.INFO, "Waiting for counterpart {0}", pair);
}
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
private void establishConnection(ClientSocket socket, ClientSocket other)
throws IOException {
Thread thread = new StreamCopier(
socket.getInputStream(), other.getOutputStream());
thread.start();
thread = new StreamCopier(
other.getInputStream(), socket.getOutputStream());
thread.start();
}
}
StreamCopier.java: a thread that reads from an InputStream and writes to an OutputStream
package matchmaker;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class StreamCopier extends Thread {
private static final Logger LOG
= Logger.getLogger(StreamCopier.class.getName());
private final InputStream in;
private final OutputStream out;
public StreamCopier(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
setDaemon(true);
}
#Override
public void run() {
LOG.info("Start stream copier");
try {
for (int b = in.read(); b != -1; b = in.read()) {
out.write(b);
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
} finally {
LOG.info("End stream copier");
try {
out.close();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
}
ClientPair.java: a pair of client IDs
package matchmaker;
public class ClientPair {
private final String client1;
private final String client2;
public ClientPair(String client1, String client2) {
this.client1 = client1;
this.client2 = client2;
}
public String getClient1() {
return client1;
}
public String getClient2() {
return client2;
}
public ClientPair opposite() {
return new ClientPair(client2, client1);
}
#Override
public int hashCode() {
int hash = 5;
hash = 73 * hash + client1.hashCode();
hash = 73 * hash + client2.hashCode();
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ClientPair other = (ClientPair) obj;
return client1.equals(other.client1) && client2.equals(other.client2);
}
#Override
public String toString() {
return "[" + client1 + "," + client2 + "]";
}
}
ReaderClient.java: a sample client that reads from the socket and writes to standard output
package matchmaker;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReaderClient {
private static final Logger LOG = Logger.getLogger(ReaderClient.class.getName());
public static void main(String[] args) {
try (ClientSocket client
= new ClientSocket("localhost", 1234, "reader", "writer")) {
Reader reader
= new InputStreamReader(client.getInputStream(), "UTF-8");
BufferedReader in = new BufferedReader(reader);
for (String s = in.readLine(); s != null; s = in.readLine()) {
System.out.println(s);
}
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
WriterClient.java: a sample client that writes to the socket
package matchmaker;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WriterClient {
private static final Logger LOG = Logger.getLogger(ReaderClient.class.getName());
public static void main(String[] args) {
try (ClientSocket client
= new ClientSocket("localhost", 1234, "writer", "reader")) {
Writer writer
= new OutputStreamWriter(client.getOutputStream(), "UTF-8");
PrintWriter out = new PrintWriter(writer);
for (int i = 0; i < 30; ++i) {
out.println("Message line " + i);
}
out.flush();
} catch (IOException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
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.