Cannot reconnect to bluetooth server without restarting bluetooth radio - java

I have an android client device that will attempt to connect to a bluetooth-enabled server and transmit data to it. So far, it's been working great except for one hitch: whenever I want to reconnect to the server after the connection was terminated, the server does not detect that a request for connection was sent by the client. If I turn off and on the bluetooth radio, and then attempt to reconnect, everything works normally. What am I doing wrong?
Here's the main Class
package org.team2180.scoutingServer;
import java.io.IOException;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import org.json.JSONObject;
import javax.bluetooth.UUID;
public class Server {
public static final UUID serviceUUID = new UUID("94f39d297d6d437d973bfba39e49d4ee", false);
public static String connectionString = "btspp://localhost:" + serviceUUID.toString() +";name=ProblemServer";
static LocalDevice locDev;
public static final JSONObject DATA = new JSONObject();
public static void main(String[] args) {
try {
locDev = LocalDevice.getLocalDevice();
System.out.println("Local Device: '" + locDev.getFriendlyName()+"' # "+locDev.getBluetoothAddress());
StreamConnectionNotifier streamConnNot = startServer();
startListening(streamConnNot);
} catch (Exception e) {
e.printStackTrace();
}
}
public static StreamConnectionNotifier startServer() throws Exception {
if(serverStarted){return null;}
boolean isNowDiscoverable = locDev.setDiscoverable(DiscoveryAgent.GIAC);
System.out.println("Local Device Discoverable: "+Boolean.toString(isNowDiscoverable));
System.out.println("Local Device URI: "+connectionString);
StreamConnectionNotifier streamConnNot = (StreamConnectionNotifier) Connector.open(connectionString);
System.out.println("Server: Created, waiting for clients . . . ");
return streamConnNot;
}
public static void startListening(StreamConnectionNotifier streamConnNot) throws IOException {
while(true) {
StreamConnection connection = streamConnNot.acceptAndOpen();
Thread connectedThread = new Thread(new ConnectionHandler(connection, TEAM_DATA));
System.out.println("Sever: found a client, placed on thread:" + connectedThread.getId());
connectedThread.start();
}
}
}
I handle each connection with its own thread based on this Class, exchanging an initial byte to determine how to handle the connection (send data to the device's database, get data from the device's database)
package org.team2180.scoutingServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.microedition.io.StreamConnection;
import javax.bluetooth.RemoteDevice;
import org.json.*;
public class ConnectionHandler implements Runnable {
final StreamConnection connection;
final JSONObject TEAM_DATA;
RemoteDevice remDev;
String deviceIndex;
public ConnectionHandler(StreamConnection connection,JSONObject TEAM_DATA) {
this.connection = connection;
this.TEAM_DATA = TEAM_DATA;
try {
this.remDev = RemoteDevice.getRemoteDevice(connection);
this.deviceIndex = remDev.getFriendlyName(true)+'#'+remDev.getBluetoothAddress();
} catch (IOException e) {
this.remDev = null;
this.deviceIndex = null;
}
}
#Override
public void run() {
try {
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(out));
BufferedReader bReader = new BufferedReader(new InputStreamReader(in));
int handshake = in.read();
if(handshake==1) {
System.out.println(deviceIndex+" will now inform you of TOP SECRET_INFO");
updateDatabase(remDev, pWriter, bReader);
System.out.println(deviceIndex+" >\n"+ TEAM_DATA.getJSONObject(deviceIndex).getInt("entryCount"));
}
} catch (Exception e) {
System.out.println(deviceIndex+"'s thread is terminating BADLY!");
try {connection.close();} catch (IOException e1) {e1.printStackTrace();}
return;
}
System.out.println(deviceIndex+"'s thread is terminating!");
return;
}
public void updateDatabase(RemoteDevice remDev, PrintWriter ex, BufferedReader in) throws IOException, JSONException {
//OK!
ex.write(1);
ex.flush();
char[] charData = new char[8192];
in.read(charData);
String data = new String(charData);
connection.close();
//Continue doing other things with data
.
.
.
Here is the Android client code to connect to the server.It is not a thread, and does block, however, this is intentional so that the user waits before leaving the connection radius
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = gatherData();
try{
bS = getSockToServer();
bS.connect();
OutputStream bsO = bS.getOutputStream();
InputStream bsI = bS.getInputStream();
bsO.write(1);//Code upload
bsO.flush();
Log.d("sendButton.onClick","sent condition code 1");
int handRespond = (int)bsI.read();
Log.d("recieved",handRespond+"");
if(handRespond == 1){
bsO.write(text.getBytes("UTF-8"));
bsO.flush();
}
}catch(Exception e){
Log.e("sendButton.onClick",e.toString());
try{
bS.close();
}catch(IOException ioE){
Log.e("sendButton.onClick{SNC}",e.toString());
}
}
}
});
My final goal would be to handle multiple devices at once (hence the usage of threads) and not have to reset the radio every time a device needs to reconnect.
My code extremely crude; I have only been working with bluecove (and bluetooth in general) for two weeks. Any advice/tricks are appreciated!

I can't relive i didn't see this before.
I need to close the socket clientside.
Whoops.

Related

Socket connection succeeds even with wrong/null URL

I am running a test using the Java socket class, but somehow my socket.connect ALWAYS connects successfully to something, even if my url variable is null or incorrect. Does anyone know why?
package ping_run_send;
import java.util.*;
import java.lang.*;
import java.net.*;
import java.io.*
import java.security.cert.*;
import javax.net.ssl.*;
public class tcpping {
private String url, status;
private Date timestamp;
private long rtime;
tcpping(String input_url){
this.url = input_url;
}
void ping() {
try{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("my proxy", 80));
Socket socket = new Socket(proxy);
long tStart = System.currentTimeMillis();
socket.connect(new InetSocketAddress(url, 80),2000);
long tEnd = System.currentTimeMillis();
rtime = tEnd-tStart;
timestamp = new Date(tStart);
InputStream sIn = socket.getInputStream();
if (sIn != null) {
status = "normal";
socket.close();
}else {
status = "error";
}
} catch(final MalformedURLException e){
status = "error";
} catch(IOException e){
status = "error";
}
}
Long get_rtime() {
return rtime;
}
Date get_timestamp() {
return timestamp;
}
String get_status() {
return status;
}
}
I also tried changing the if statement from isConnected() to
InputStream sIn = socket.getInputStream();
if (sIn != null) {
status = "normal";
socket.close();
}else {
status = "error";
}
But nothing seems to be have changed on its ability to detect connection error.
my testing file:
package ping_run_send;
import java.lang.*;
import java.util.*;
import java.io.*;
import ping_run_send.httpping;
public class main {
public static void main(String[] args){
String url = "http://google.com";
//urls like "",http://gowegwgwoJOIJOI03OINEPJPogle.#(*%" all works somehow
tcpping testTcp = new tcpping(url);
testTcp.ping();
System.out.println("tcp ping:");
System.out.println(testTcp.get_rtime());
System.out.println(testTcp.get_timestamp());
System.out.println(testTcp.get_status());
}
}
It is connecting to the Proxy. When you specify a Proxy the connection is made to the Proxy and the Proxy itself handles the connections to the real endpoint.

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.

Java code does not get udp packet in a specific port

I am trying to read some packets from a port 2020 in my server. I have run tcpdump -r eth1 port 2020 and can find that udp packets are coming into the port. Following is the screenshot :
But when i try to read those packets from the java code, i do not get any data. Following is my java code :
package packetreceiver;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import main.Main;
import propertyfilereader.PropertyFileReader;
import org.apache.log4j.Logger;
import com.sun.jmx.snmp.SnmpMessage;
import alarmprocessor.AlarmProcessor;
public class UDPPacketReceiver extends Thread {
private DatagramSocket socket = null;
private Logger logger = Logger.getLogger(UDPPacketReceiver.class);
public boolean dynamicKey = false;
private UDPPacketReceiver() {
try {
logger.debug(" port : " + Main.orgPort);
logger.debug(" ip : " + Main.orgBindIPStr);
logger.debug("creating socket");
socket = new DatagramSocket(null);
//socket = new DatagramSocket(38567);
InetSocketAddress address = new InetSocketAddress(2020);
socket.bind(address);
logger.debug("Receiver Socket created successfully");
} catch (Exception e) {
logger.fatal("Exception at creating socket ", e);
logger.fatal("Exiting successfully ");
System.exit(0);
}
this.running = true;
}
static UDPPacketReceiver instance = null;
public static UDPPacketReceiver getInstance() {
if (instance == null) {
createInstance();
}
return instance;
}
boolean running = false;
private static synchronized UDPPacketReceiver createInstance() {
if (instance == null) {
instance = new UDPPacketReceiver();
}
return instance;
}
public void run() {
byte[] data = new byte[2048];
DatagramPacket packet = new DatagramPacket(data, data.length);
while (this.running) {
try {
logger.debug("waiting for received data");
this.socket.receive(packet);
int length = packet.getLength();
logger.debug("length:"+length);
logger.debug("data:"+new String(packet.getData()));
} catch (Exception e) {
if ((this.socket == null) || (this.socket.isClosed())) {
this.running = false;
} else {
this.logger.fatal("Error in receiving UDP packet:", e);
}
}
}
}
public void shutdown() {
this.running = false;
try {
if ((this.socket != null) && (!this.socket.isClosed())) {
this.socket.close();
}
} catch (Exception localException) {
}
this.socket = null;
}
}
I have searched in stackeoverflow and other posts but could not find any solution. Can you please help me.
Regards,
Tanvir
Check with the netstat command to see whether your application is actually bound to the correct IP/interface:
> sudo netstat -tunlp | grep 2020
works in linux.
You can also change this line:
InetSocketAddress address = new InetSocketAddress(172.22.49.116, 2020);

How to create a java Server that accepts client connections and then build a relay connection for a client pair

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);
}
}
}

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