Basically, I've been working on a wireless mouse that utilizes bluetooth OR wifi. I've gotten everything working including reading and writing messages. However, the rate at which data transfers through bluetooth is too slow to compensate. I've looked all over the place and I can't figure out what is causing this speed. I am using a dedicated thread to do all the writing operations on.
Here is my ConnectedThread code (almost exactly like in the Android SDK example)
package com.tutorials.jurko.androidmouse;
import android.bluetooth.BluetoothSocket;
import android.net.ConnectivityManager;
import java.io.BufferedOutputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Jurko on 14/02/2015.
*/
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final BufferedOutputStream mmOutStream;
public static int count = 0;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = new BufferedOutputStream(tmpOut);
}
public void write(Byte[] bytes) {
count++;
try {
byte x = bytes[0].byteValue();
byte y = bytes[1].byteValue();
System.out.println("Count: " + count);
byte buf[] = {x, y};
mmOutStream.write(buf);
mmOutStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my server code (Receiving messages)
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import java.awt.*;
import java.awt.event.InputEvent;
import java.io.*;
/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class SimpleSPPServer {
//start server
private void startServer() throws IOException, AWTException {
Robot r = new Robot();
//Create a UUID for SPP
UUID uuid = new UUID("1101", true);
//Create the servicve url
String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: "+dev.getBluetoothAddress());
System.out.println("Remote device name: "+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
byte[] lineRead = new byte[2];
while(inStream.read(lineRead) != -1) {
System.out.println(lineRead[0] + " " + lineRead[1]);
// Code to control mouse here
}
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write("Response String from SPP Server\r\n");
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException, AWTException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: "+localDevice.getBluetoothAddress());
System.out.println("Name: "+localDevice.getFriendlyName());
SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
sampleSPPServer.startServer();
}
}
Someone asked for an answer, so here it is. Out of complete coincidence (and boredom I guess), I decided to fix ALL of the warnings Android Studio was giving me.
One of the warnings indicated that I was instantiating new objects in the onDraw function. Turns out that the bluetooth was not slow, but in fact the onDraw took so long it delayed the transmission of new messages, making it appear as if a consistent lag was present.
tl;dr: Don't instantiate new objects in your onDraw function.
Related
I created restful API(with maven) which connect to MySQL. I want to connect with the Java socket server I created earlier. But I couldn't figure out how to do this. I tried to connect with HttpURLConnection over Server.java but it didn't connect yet. Is it a good way to connect? Or should i try different way for this? And also I created new maven project and putted Server.Java and Client.Java in it. But it is a just attempt. I am not sure is it necessary or not.
Server.JAVA
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Server {
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
// System.out.println("Client accepted");
// HttpURLConnection attempt
URL url = new URL("http://localhost:8080/update/3");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("PUT");
http.setRequestProperty("Content-Type", "application/json");
http.setDoOutput(true);
OutputStream stream = http.getOutputStream();
String data = "{\n \"firstName\":\"Can\",\n \"lastName\":\"Doe\",\n \"occupation\":\"xxx\"\n}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
stream.write(out);
System.out.println(http.getResponseCode() + http.getResponseMessage());
http.disconnect();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Stop" is sent
while (!line.equals("Stop"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server( 5000);
}
}
Im having Spring Boot Application for communication between Machines (tcp Clients) and TCP Server (localhost). I am able to communicate with one machine/client, but I cant communicate with 2 or more machines.
Therefore I start my Spring Boot Application:
package com.example.workflow;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.IOException;
#SpringBootApplication
public class Application {
public static void main(String[] args) throws IOException {
Runnable serverZyklisch = new ServerZyklisch();
Runnable serverAzyklisch = new ServerAzyklisch();
for (int i = 0; i < 4; i++) {
new Thread(serverZyklisch).start();
new Thread(serverAzyklisch).start();
}
SpringApplication.run(Application.class);
}
}
There I have different Threads started, so that the clients (for example 10.50.12.174 = Press, 10.50.12.204 = Drill) can connect to TCP Server over Socket Connection.
My ServerAzyklisch class is like this:
package com.example.workflow;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerAzyklisch implements Runnable, JavaDelegate {
int count = 0;
private final ServerSocket ssocket;
static String param = StartTCPServersDelegate.parameter;
HexToByteConverter hexToByteConverter = new HexToByteConverter();
// 2 TCP Server starten Port 2000, Port 2001
public ServerAzyklisch(String Pparam) throws IOException {
ssocket = new ServerSocket(2000);
param = Pparam;
}
public ServerAzyklisch() throws IOException {
ssocket = new ServerSocket(2000);
}
public void run() {
byte[] buf = new byte[1];
System.out.println(param+"Paraaam");
InputStream in;
OutputStream out = null;
Socket socket = null;
//Thread immer aktiv
int n = 0;
while(true){
try {
// Wartet auf Socket Verbindung
System.out.println("Server is listening on port "+ ssocket.getLocalPort());
socket = ssocket.accept();
count++;
System.out.println("Countet clients: "+count);
socket.setSoLinger(true, 1000);
System.out.println("Sockeport: "+socket.getLocalPort());
System.out.println("Connection from " + socket.getInetAddress().toString());
//Inputstream
in = socket.getInputStream();
//Outputstream
out = socket.getOutputStream();
//Datenpuffer deklarieren (anlegen)
byte []data = new byte[132];
byte[]Pressen1hexdump110 = hexToByteConverter.hexStringToByteArray("33333333003d0064000600000004004001c9c78900010000006e0000000000000000000000000001000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"+param);
byte[]Pressen2hexdump = hexToByteConverter.hexStringToByteArray("3333333300400065000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
byte[]Pressen3hexdump = hexToByteConverter.hexStringToByteArray("3333333300400065001400000000004001c9c6e900010000006e000000000000000000000000000100000000001e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
in.read(buf);
while (buf[0] != -1) {
out.write(Pressen1hexdump110);
out.write(Pressen2hexdump);
out.write(Pressen3hexdump);
}
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void execute(DelegateExecution delegateExecution) throws IOException {
}
}
Now I want to outsource the "while loop" (with out.write) in other Classes to use the connection to Socket like in ServerAzyklisch run method.
Therefore I wrote for example a Class Presse.java
package com.example.workflow;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Presse implements JavaDelegate {
ServerSocket ssocket;
private HexToByteConverter hexToByteConverter = new HexToByteConverter();
Socket socket;
InputStream in;
OutputStream out;
byte[]Pressen1hexdump110 = hexToByteConverter.hexStringToByteArray("33333333003d0064000600000004004001c9c78900010000006e00000000000000000000000000010000000000140000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005");
byte[]Pressen2hexdump = hexToByteConverter.hexStringToByteArray("3333333300400065000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
byte[]Pressen3hexdump = hexToByteConverter.hexStringToByteArray("3333333300400065001400000000004001c9c6e900010000006e000000000000000000000000000100000000001e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
public Presse() throws IOException {
ssocket = new ServerSocket(2000);
socket = ssocket.accept();
//Inputstream
in = socket.getInputStream();
//Outputstream
out = socket.getOutputStream();
}
public void sendMessage(InputStream in, OutputStream out, byte[]message) throws IOException {
out.write(Pressen1hexdump110);
out.write(Pressen2hexdump);
out.write(Pressen3hexdump);
socket.close();
}
#Override
public void execute(DelegateExecution delegateExecution) throws Exception {
PostRequestDelegate postRequestDelegate = new PostRequestDelegate();
postRequestDelegate.post();
}
}
I want to send my 3 messages from this class, like in ServerAzyklisch class. But it throws Error because:
Caused by: java.net.BindException: Address already in use: NET_Bind
I know this because is I do Socket.accept a second time, but I dont understand how I can achieve this to work. Do I have to close socket connection ? If yes where and with which Java Command ?
If you want to have more than one instances of "Presse" in your program, the very least you'll need to remove ServerSocket from it. Instead, you should accept the connection from the client somewhere else, and pass the client socket to the Presse constructor:
public Presse(Socket clientSocket) throws IOException {
this.socket = clientSocket;
//Inputstream
in = socket.getInputStream();
//Outputstream
out = socket.getOutputStream();
}
Usually you want to create only one ServerSocket, and call accept on it in a loop. To allow more than one client to connect at a time, communicate with the client in a separate thread. This way the server can go and accept a new connection. Here's a skeleton example of how to use a thread pool for this:
int maxClients = 10;
ExecutorService threadPool = Executors.newFixedThreadPool(maxClients);
ServerSocket serverSocket = new ServerSocket(2000);
while (true) {
Socket clientSocket = serverSocket.accept();
threadPool.submit(() -> {
// Communicate with clientSocket, for example:
Presse p = new Presse(clientSocket);
// You'll want to have this code in a separate method
});
}
I am new to java and network programming for the most part. I want to write a program that automatically backs up my texts to my computer whenever my phone connects to my home wifi.
I am working on creating java classes that will handle sending data over the network. Using some questions found here, I came up with this implementation but I have some questions regarding some of the methods used in what I learned from.
Two Questions Regarding this code
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call or is it when the BufferStream readLine() is checked? Does accept just grab data and throw it into the buffer? null implying the data grabbed was not a signal sent from a client?
Does the accept() method block execution of the code until a connection attempt is made from a client?
Thanks!
KServ
//Used to launch the server
public class KServ {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java KServ <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
KServer server = new KServer(port);
while (true) { //added this to keep the server polling for new data
server.run();
}
}
}
KServer
//Server class. Should handle data incoming
import java.net.*;
import java.io.*;
public class KServer {
private int port;
public KServer(int PORT) {
port = PORT;
}
public void run() {
try (
ServerSocket sSocket = new ServerSocket(port);
Socket cSocket = sSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
) {
String input;
while ((input = in.readLine()) != null) {
System.out.println(input);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port " + port + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
Client
//launches KClient object and uses it to send input from console to the server
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java Client <ip number> <port number>");
System.exit(1);
}
String ip = args[0];
int port = Integer.parseInt(args[1]);
KClient client = new KClient(ip,port);
String msg;
Scanner inStream = new Scanner(System.in);
while((msg = inStream.nextLine()).length() > 0) {
client.sendText(msg);
}
}
}
KClient
//Will be used to establish connection with server and send data from phone
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class KClient {
private String server;
private int port;
public KClient(String Server,int Port) {
server = Server;
port = Port;
}
public void sendFile(String fileName) {
File file = new File(fileName);
FileInputStream fileInputStream;
BufferedInputStream bufferedInputStream;
OutputStream outputStream;
try {
client = new Socket(server,port);
byte[] bytes = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(bytes, 0, bytes.length);
outputStream = client.getOutputStream();
outputStream.write(bytes,0,bytes.length);
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Socket client;
private OutputStreamWriter outputStreamWriter;
public void sendText(String msg) {
System.out.println("Send Message!");
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(server,port);
outputStreamWriter = new OutputStreamWriter(client.getOutputStream(), "ISO-8859-1");
outputStreamWriter.write(msg);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
BufferedReader inStream;
public boolean Shake() {
try {
client = new Socket(server,port);
inStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
Unanswerable. Ask the author. Both sends can block. As the file is presumably longer than the text, it would have made more sense to do it the other way round.
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call
No.
or is it when the BufferStream readLine() is checked?
Yes.
Does accept just grab data and throw it into the buffer?
No. It grabs a connection and returns it as a socket. Nothing to do with data whatsoever.
null implying the data grabbed was not a signal sent from a client?
You seem to be actually asking about BufferedReader.readLine() here, not ServerSocket.accept(), which doesn't return null. readLine() returns null when there is no pending data to be read and the peer has closed the connection.
Does the accept() method block execution of the code until a connection attempt is made from a client?
More or less. It blocks until there is a complete connection waiting to be accepted, which isn't quite the same thing, as there is a queue.
I will add that you have copied, or written, some truly terrible code here. There are much better examples.
Server and client communicating with my own protocol which looks like XMPP. I should to realize chat application. So when one user write String it immedeatly should be sended to other client through the server. I have method sendToAll on server. But user see the message of other user only when it press enter.
How can user receive messages without pressing enter button?
So this is my client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.log4j.Logger;
import dataart.practice.protocols.XMLProtocol;
public class Client {
public static final String SERVER_HOST = "localhost";
public static final Integer SERVER_PORT = 4444;
public static final Logger LOG = Logger.getLogger(Client.class);
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader inu;
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Client side");
XMLProtocol protocol = new XMLProtocol();
Socket fromserver = null;
fromserver = new Socket(SERVER_HOST, SERVER_PORT);
in = new BufferedReader(new InputStreamReader(fromserver.getInputStream()));
out = new PrintWriter(fromserver.getOutputStream(), true);
inu = new BufferedReader(new InputStreamReader(System.in));
String fuser, fserver;
while (true){
if(in.ready()){//fserver = in.readLine()) != null) {
System.out.println("asdasdsd");
fuser = inu.readLine();
if (fuser != null) {
if (fuser.equalsIgnoreCase("close"))
break;
if (fuser.equalsIgnoreCase("exit"))
break;
protocol.setComId((long) 0);
protocol.setContent(fuser);
protocol.setLogin("Guest");
try {
JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
jaxbMarshaller.marshal(protocol, out);
out.flush();
} catch (JAXBException e) {
LOG.error("Error while processing protocol" + e);
}
}
}
}
out.close();
in.close();
inu.close();
fromserver.close();
}
}
And Server with ServerThread.
public static void main(String[] args) throws IOException {
LOG.trace("Server started");
ServerSocket s = new ServerSocket(SERVER_PORT);
try {
while (true) {
LOG.trace("Waiting for connections...");
Socket socket = s.accept();
try {
// new ServerThread(socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
userCounter++;
addUser("Guest" + userCounter, out);
LOG.trace("User " + userCounter + " has been added!");
exec.execute(new ServerThread(socket, in, out));
} catch (IOException e) {
socket.close();
}
}
} finally {
s.close();
}
}
ServerThread.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.Socket;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.apache.log4j.Logger;
import dataart.practice.protocols.XMLProtocol;
import dataart.practice.serverUtils.Commands;
public class ServerThread implements Runnable {
private static final Logger LOG = Logger.getLogger(ServerThread.class);
private XMLProtocol protocol;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String buffer = "";// may be exist another. way but it's not working
private Boolean login = false;
public ServerThread(Socket s, BufferedReader in, PrintWriter out) throws IOException {
this.in = in;
this.out = out;
out.println("</XMLProtocol>");
socket = s;
new Thread(this);
}
public void run() {
try {
while (true) {
if ((buffer = in.readLine()) != null) {
if (buffer.endsWith("</XMLProtocol>")) {
protocol = getProtocol(buffer);
//Server.onlineUserList.put(protocol.getLogin(), out);
/* if (!login){
out.println("Maybe login first?");
}
*/
LOG.trace("Getting message from user: " + protocol.getLogin() + " recived message: " + protocol.getContent());
///out.println(protocol.getLogin() + " says:" + protocol.getContent());
Server.sendToAll(protocol.getContent()+"</XMLProtocol>");
} else {
LOG.trace("Nop protocol do not send with it end");
}
}
}
} catch (IOException e) {
LOG.error("Error in reading from stream: " + e);
} catch (JAXBException e) {
LOG.error("Error in Marshalling: " + e);
} finally {
try {
socket.close();
LOG.trace("Socket closed");
} catch (IOException e) {
LOG.error("Socket no closed" + e);
}
}
}
public XMLProtocol getProtocol(String buffer) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (XMLProtocol) jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(buffer)));
}
public Boolean loginIn(XMLProtocol protocol) {
return true;
}
}
You will need to multi-thread both the client and server. The client will need one thread that listens for messages from the server and writes them to his/her screen and one thread that waits for his/her keyboard input and sends it to the server. Likewise for each connection to the server, it will need a thread waiting for input from the client and one thread sending output from other users to the client.
The reason you don't see incoming messages until you press enter is because of the client while loop. It's commented out now, but it looks like your loop used to:
- Read incoming messages from server
- Read input from keyboard
- Send input to server
So you read whatever was available from the server, and then the client waits for more keyboard input before reading from the server again (in the next iteration).
Another word of advice, from my understanding, creating JAXBContext can be an expensive operation. You don't need to recreate it every time you send a message. Consider initializing one in your server and client and then reusing it for each marshall/unmarshall.
Try this,
Do Not use BufferedReader() with PrintWriter..... PrintWriter is itself the Bridge between byte level socket data and character form.
Eg:
I am showing for a single client, use the while loop for n nos of clients
ServerSocket s = new ServerSocket(4444);
Socket incoming = s.accept();
OutputStream output = s.getOutputStream();
PrintWriter pw = new PrintWriter(output,true);
System.out.println(pw.write(new Scanner(System.in).nextLine()));
I am trying to write an application using Java that will allow me to transfer files between a server and a client that requests the file. I plan to do it using sockets. My algorithm is somewhat like this:
On Server:
Create the connection between client and server.
Once connected find the file u need to send to client.
Then send the size of file to client.
Then send file broken down in parts.
On Client
After connection is created, ask for the file.
Receive the file size, then accept data till u reach file size.
Stop.
Please correct me if i am wrong somewhere in the algorithm
This isn't really an "algorithm" question; you're designing a (simple) protocol. What you've described sounds reasonable, but it's too vague to implement. You need to be more specific. For example, some things you need to decide:
How does the receiving program know what filename it should save to? Should that be sent through the socket, or should it just ask the user?
How is the file size transmitted?
Is it a character string? If so, how is its length indicated? (With a null terminator? A newline?)
Is it a binary value? If so, how big? (32 bits or 64?) What endianness?
What does "broken down in parts" mean? If you're writing to a TCP socket, you don't need to worry about packet boundaries; TCP takes care of that.
Does the recipient send anything back, like a success or failure indication?
What happens when the whole file has been transmitted?
Should both ends assume that the connection must be closed?
Or can you send multiple files through a single connection? If so, how does the sender indicate that another file will follow?
Also, you're using the terms "client" and "server" backward. Typically the "client" is the machine that initiates a connection to a server, and the "server" is the machine that waits for connections from clients.
You can also add Acknowledgement from server once a particular part of the file is recieved,
similar to what we have in HTTP protocol , that would ensure proper delivery of the file has been received on the server.
Here is the method that I use, it uses the socket's input and output streams to send and receive the files, and when it's done, it will automatically restart the server and reconnect to it from the client.
Server Code:
package app.server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Functions
{
private static ServerSocket server;
private static Socket socket;
public static void startServer(int port)
{
try
{
server = new ServerSocket(port);
socket = server.accept();
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void restartServer()
{
new Thread()
{
#Override
public void run()
{
try
{
socket = server.accept();
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
public static void sendFile(String inputFilePath)
{
FileInputStream fis;
BufferedInputStream bis;
OutputStream os;
BufferedOutputStream bos;
try
{
File input = new File(inputFilePath);
fis = new FileInputStream(input);
bis = new BufferedInputStream(fis);
os = socket.getOutputStream();
bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int data;
while(true)
{
data = bis.read(buffer);
if(data != -1)
{
bos.write(buffer, 0, 1024);
}
else
{
bis.close();
bos.close();
break;
}
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
restartServer();
}
}
Client Code:
package app.client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Functions
{
private static Socket socket;
private static String hostName;
private static int portNumber;
public static void connectToServer(String host, int port)
{
new Thread()
{
#Override
public void run()
{
try
{
hostName = host;
portNumber = port;
socket = new Socket(host, port);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
private static void reconnectToServer()
{
try
{
socket = new Socket(hostName, portNumber);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void receiveFile(String outputFilePath)
{
InputStream is;
BufferedInputStream bis;
FileOutputStream fos;
BufferedOutputStream bos;
try
{
File output = new File(outputFilePath);
is = socket.getInputStream();
bis = new BufferedInputStream(is);
fos = new FileOutputStream(output);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int data;
while(true)
{
data = bis.read(buffer);
if(data != -1)
{
bos.write(buffer, 0, 1024);
}
else
{
bis.close();
bos.close();
break;
}
}
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
reconnectToServer();
}
}
This method works very well, I use it for my server and client file transfer program, all you need to do is enter the Server Host's IP address and choose a port number (I use 8888).