I don't know what's wrong with the code as it always resets the connection when I send an input from Client to Server. The error report indicates problem on get.readLine() on Client code.
This is the code on Client Side:
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class Client
{
public static void main(String[] args) throws UnknownHostException, IOException
{
String hostName = "localhost";
Socket client = null;
try{
client = new Socket(hostName, 9972);
}catch(UnknownHostException e) {
System.err.println("Host unknown. Cannot establish connection");
} catch (IOException e) {
System.err.println("Cannot establish connection. Server may not be up." + e.getMessage());
}
PrintWriter send = new PrintWriter(client.getOutputStream(), true);
BufferedReader get = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a 7-bits binary to send: ");
String input;
while((input = read.readLine()) != null)
{
String codeWord = addParity(input);
send.println(codeWord);
System.out.println("Server responds: " + get.readLine());
}
send.close();
get.close();
read.close();
client.close();
}
public static String addParity(String data)
{
//Some code block here
}
}
This is the code on Server Side:
import java.io.*;
import java.net.*;
import java.util.Random;
import java.util.ArrayList;
public class Server
{
public static void main(String[] args) throws IOException
{
int port = 9972;
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
PrintWriter send = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader get = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String input;
while((input = get.readLine()) != null)
{
if(input.length() == 11 && input.matches("[01]+"))
{
String data = "";
Random rand = new Random();
int change = rand.nextInt(1);
for(int I = 0; I < change; i++)
{
data = modify(input);
}
String result = HammingCheck(data);
send.println(result);
}
else
send.println("Input is invalid. Echo: " + input);
if(input.equals("bye"))
break;
}
send.close();
get.close();
clientSocket.close();
serverSocket.close();
}
public static String modify(String input)
{
//Some code to modify the string
}
public static String HammingCheck(String data)
{
//Some code to perform hamming code checking
}
public static String removeParity(String data)
{
//some code to remove parity bits
}
}
This is the error report:
Attempting to connect to server at host: localhost
Connection established.
Enter a 7-bits binary string as message to server: 1111111
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at ClientSide.Client.main(Client.java:35)
Related
Objective - I want to send the entered text in the java (PC) project to the android app which displays this text.The PC is connected to wifi
hotspot created by the android mobile.
The PC/client java project code:
public class EcsDemo {
public static void main(String[] args) {
System.out.println("Enter SSID to connect :");
Scanner in = new Scanner(System.in);
String ssid = in.nextLine();
System.out.println("You entered ssid " + ssid);
System.out.println("Connecting to ssid ..");
DosCommand.runCmd(DosCommand.connectToProfile(ssid));
// netsh wlan connect name=
System.out.println("initializing tcp client ..");
try {
TCPClient.startTCpClient();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TCPClient {
public static void startTCpClient() throws UnknownHostException, IOException{
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}
Android app/Server code:
public class MainActivity extends Activity {
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "starting server");
new ServerAsyncTask().execute();
}
}
public class ServerAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
TCPServer.startTCPServer();// initTCPserver();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public static void startTCPServer() throws IOException{
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
Log.i("startTCPServer","TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
Log.i("startTCPServer"," THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
// System.out.println("SEND(Type Q or q to Quit):");
// toclient = inFromUser.readLine();
//
// if (toclient.equals("q") || toclient.equals("Q")) {
// outToClient.println(toclient);
// connected.close();
// break;
// } else {
// outToClient.println(toclient);
// }
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
After running the android app and then when I run the java project I get the following exception:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.expressecs.javademo.TCPClient.startTCpClient(TCPClient.java:15)
at com.expressecs.javademo.EcsDemo.main(EcsDemo.java:41)
I have referred to the following links:
java.net.ConnectException: Connection refused
Thanks!
There is nothing listening at the IP:port you are trying to connect to.
Your server didn't start, or is listening to a different port, or is bound to 127.0.0.1 instead of 0.0.0.0 or a public IP address.
The goal is to develop a web server that when accessed via a web browser will return the HTTP request message that it receives.
I run the program from a virtual machine environment and access the server from my local machine. The code I have is below. When I type in my IP address while the server is running, I just get a Null Pointer Exception. Any guidance would be greatly appreciated.
import java.io.*;
import java.net.*;
import java.util.*;
public final class proj1 {
public static void main(String[] args) throws Exception{
int port = 9000;
ServerSocket socket = new ServerSocket(port);
while(true) {
Socket connection = socket.accept();
HttpRequest request = new HttpRequest(connection);
Thread thread = new Thread(request);
thread.start();
}
}
}
final class HttpRequest implements Runnable {
//Declare Variables
final static String CRLF = "\r\n";
Socket socket;
//Constructor
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
//Unimplemented Runnable Method
#Override
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
//Reference Socket Input and Output Streams
InputStream is = socket.getInputStream();
DataOutputStream os = null;
//Input Stream Filters
BufferedReader br = new BufferedReader(null);
//Request Line of HTTP Request Message
String requestLine = br.readLine();
//Extract FileName From Request Line
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken();
String fileName = tokens.nextToken();
fileName = "." + fileName;
//Open Requested File
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
//Debug
System.out.println(requestLine);
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
//Construct Response Message
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "statusLine";
contentTypeLine = "Content-Type: " + contentType(fileName) + CRLF;
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
contentTypeLine = "Content-Type: text/html" + CRLF;
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>" + "<BODY>Not Found</BODY></HTML>";
}
//Send Lines
os.writeBytes(statusLine);
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
//Send Entity Body
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody);
}
//Close Streams and Sockets
os.close();
br.close();
socket.close();
}
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
return "application/octet-stream";
}
}
Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at proj1.main(proj1.java:10)
That is the error code when I try to run the program in eclipse... When I run the code in my virtual machine, it runs fine but whenever I access the IP address of the server on my machine, I get no response message and a Null Pointer Exception on the virtual machine.
new BufferedReader(null) will always throw NullPointerException. What did you except?
By the way, this is always a bad idea:
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
If you don't know what to do with the exception, at least re-throw it to retain the stack trace:
try {
processRequest();
} catch (Exception e) {
throw new RuntimeException(e);
}
This would have lead you to the line throwing the exception.
I have been trying to play around with Java's Socket class and I have hit a tough spot. I have three classes: EchoServerTemplate, ConcurrentServer, and EchoClient.
I want to send a website(www.google.com) from a client to the server and then have the server return the IP address. I think I am extremely close, but I do not know how BufferedStreamer in Java works well enough to figure out the error messages.
Here is my code for all three classes:
EchoServerTemplate (This is where I want the Web Address to be translated):
import java.net.*;
import java.io.*;
public class EchoServerTemplate extends Thread
{
public static final int DEFAULT_PORT = 6007;
public static final int BUFFER_SIZE = 256;
Socket clientSocket;
EchoServerTemplate(Socket cs){
clientSocket = cs;
}
public void run(){
InputStream fromClient = null;
OutputStream toClient = null;
byte[] buffer = new byte[BUFFER_SIZE];
String printaddress = null;
try {
while(true){
PrintWriter pout = new PrintWriter(clientSocket.getOutputStream(), true);
fromClient = new BufferedInputStream(clientSocket.getInputStream());
try {
InetAddress address = InetAddress.getByName(fromClient.toString());
printaddress = address.toString();
}
catch(UnknownHostException e){
System.out.println(e);
}
toClient = new BufferedOutputStream(clientSocket.getOutputStream());
while (printaddress != null) {
toClient.write(printaddress.getBytes("UTF-8"));
toClient.flush();
printaddress = null;
}
fromClient.close();
toClient.close();
clientSocket.close();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
ConcurrentServer:
import java.io.*;
import java.net.*;
public class ConcurrentServer {
public static final int BUFFER_SIZE = 256;
public static void main(String[] args) throws IOException {
try {
int serverPortNumber = 6007;
ServerSocket sock = new ServerSocket(serverPortNumber);
while (true) {
Socket clientSocket = sock.accept();
EchoServerTemplate thread = new EchoServerTemplate(clientSocket);
thread.start();
}
}
catch (IOException ioe) {
ioe.printStackTrace();}
}
}
EchoClient:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("127.0.0.1", 6007);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: ");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to the host.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("IP Address: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
The task I accomplished before this was just having the ConcurrentServer repeat what was typed on the client. In modifying the code I may have accidentally messed something up. Here are the error messages I am receiving:
run: www.google.com Exception in thread "main"
java.net.SocketException: Connection reset at
java.net.SocketInputStream.read(SocketInputStream.java:189) at
java.net.SocketInputStream.read(SocketInputStream.java:121) at
sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at
sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at
sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at
java.io.InputStreamReader.read(InputStreamReader.java:184) at
java.io.BufferedReader.fill(BufferedReader.java:154) at
java.io.BufferedReader.readLine(BufferedReader.java:317) at
java.io.BufferedReader.readLine(BufferedReader.java:382) at
EchoClient.main(EchoClient.java:31) Java Result: 1 BUILD SUCCESSFUL
(total time: 4 seconds)
Any help is appreciated. If you need any more information, please let me know.
I'm just trying to test sending bytes over a TCP socket connection, I know it wasn't really meant for that but I'm just trying to figure out whether this is possible or not
what i'm trying to do:
get bytes from a string on client
sent it as bytes to the server
get the bytes on the server and decode it back to the original string
Client:
package ByteClientServer;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
public class Client {
String hostAddress = "localhost";
int port = 1010;
public Client()
{
try {
Socket socket = new Socket(hostAddress, port);
String test = "hello"; //dycrypt bytes from this string on server side
byte[] byteArray = test.getBytes();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.write(byteArray);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Client();
}
}
Server:
package ByteClientServer;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args)
{
try
{
ServerSocket server = new ServerSocket(1010);
server.setSoTimeout(0);
Socket connectionToClient = server.accept();
InputStream is = connectionToClient.getInputStream();
DataInputStream dis = new DataInputStream(is);
byte[] data = dis.readUTF().getBytes();
//dis.readFully(data, 0, data.length);
String s = new String(data);
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
//System.err.println("Server was terminated.");
}
}
}
it doesn't like this line on server:
byte[] data = dis.readUTF().getBytes();
and throws the exception:
java.net.SocketException: Connection reset at
java.net.SocketInputStream.read(Unknown Source) at
java.net.SocketInputStream.read(Unknown Source) at
java.io.DataInputStream.readFully(Unknown Source) at
java.io.DataInputStream.readUTF(Unknown Source) at
java.io.DataInputStream.readUTF(Unknown Source) at
ByteClientServer.Server.main(Server.java:21)
If you want to use readUTF then you need to use writeUTF. if you want to just write bytes, then you need to read just bytes.
You are writing bytes with default encoding then reading it as UTF-8 encoding. Thats the issue.
Here is John Skeets blog explaining how to debug these errors and some pitfalls
I came up with a simple workaround
Client:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args)
{
String hostAddress = "localhost";
int port = 8080;
Socket socket = null;
String test = "hello"; //decode bytes from this string on the server
byte[] byteArray = test.getBytes();
try
{
socket = new Socket(hostAddress, port);
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.write(byteArray, 0, byteArray.length);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws SocketException
{
try
{
ServerSocket server = new ServerSocket(8080);
server.setSoTimeout(0);
Socket connectionToClient = server.accept();
InputStream is = connectionToClient.getInputStream();
DataInputStream dis = new DataInputStream(is);
int buffersize = connectionToClient.getReceiveBufferSize();
byte[] bytes = new byte[buffersize];
if(dis.read(bytes) > 0)
{
String s = new String(bytes);
System.out.print(s);
}
dis.close();
server.close();
}
catch(IOException e)
{
e.printStackTrace();
System.err.println("Server was terminated.");
}
}
}
This is an assignment.
Im looking for a bit of advice as to where i am going wrong here. My aim is to read text from a file, send it to the server and write that text into a new file.
Problem being im not exactly sure how to do it, I have looked at many examples none of which being much help.
To explain the program as is. The user would be asked to input a code which relates to an if statemnt of that code. The one i want to focus on is code 200 which is the upload file to server code.
When i run the code i have i get this error below. Could someone explain to me where i am going wrong, I'd appreciate it.
Connection request made
Enter Code: 100 = Login, 200 = Upload, 400 = Logout:
200
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at MyStreamSocket.receiveMessage(MyStreamSocket.java:50)
at EchoClientHelper2.getEcho(EchoClientHelper2.java:34)
at EchoClient2.main(EchoClient2.java:99)
And this error on the server:
Waiting for a connection.
connection accepted
message received: 200
java.net.SocketException: Socket is not connected
at java.net.Socket.getInputStream(Unknown Source)
at EchoServer2.main(EchoServer2.java:71)
Your MyStreamSocket class does not need to extend Socket. The mysterious error message is because the Socket represented by MyStreamSocket is never connected to anything. The Socket referenced by its socket member is the one that is connected. Hence when you get the input stream from MyStreamSocket it genuinely is not connected. That causes an error, which means the client shuts down. That causes the socket to close, which the server duly reports
The use of BufferedReader is going to cause you problems. It always reads as much as it can into its buffer, so at the start of a file transfer it will read the "200" message and then the first few Kb of the file being sent which will get parsed as character data. The result will be a whole heap of bugs.
I suggest you get rid of BufferedReader right now and use DataInputStream and DataOutputStream instead. You can use the writeUTF and readUTF methods to send your textual commands. To send the file I would suggest a simple chunk encoding.
It's probably easiest if I give you code.
First your client class.
import java.io.*;
import java.net.InetAddress;
public class EchoClient2 {
public static void main(String[] args) {
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
File file = new File("C:\\MyFile.txt");
try {
System.out.println("Welcome to the Echo client.\n"
+ "What is the name of the server host?");
String hostName = br.readLine();
if( hostName.length() == 0 ) // if user did not enter a name
hostName = "localhost"; // use the default host name
System.out.println("What is the port number of the server host?");
String portNum = br.readLine();
if( portNum.length() == 0 ) portNum = "7"; // default port number
MyStreamSocket socket = new MyStreamSocket(
InetAddress.getByName(hostName), Integer.parseInt(portNum));
boolean done = false;
String echo;
while( !done ) {
System.out.println("Enter Code: 100 = Login, 200 = Upload, 400 = Logout: ");
String message = br.readLine();
boolean messageOK = false;
if( message.equals("100") ) {
messageOK = true;
System.out.println("Enter T-Number: (Use Uppercase 'T')");
String login = br.readLine();
if( login.charAt(0) == 'T' ) {
System.out.println("Login Worked fantastically");
} else {
System.out.println("Login Failed");
}
socket.sendMessage("100");
}
if( message.equals("200") ) {
messageOK = true;
socket.sendMessage("200");
socket.sendFile(file);
}
if( (message.trim()).equals("400") ) {
messageOK = true;
System.out.println("Logged Out");
done = true;
socket.sendMessage("400");
socket.close();
break;
}
if( ! messageOK ) {
System.out.println("Invalid input");
continue;
}
// get reply from server
echo = socket.receiveMessage();
System.out.println(echo);
} // end while
} // end try
catch (Exception ex) {
ex.printStackTrace();
} // end catch
} // end main
} // end class
Then your server class:
import java.io.*;
import java.net.*;
public class EchoServer2 {
static final String loginMessage = "Logged In";
static final String logoutMessage = "Logged Out";
public static void main(String[] args) {
int serverPort = 7; // default port
String message;
if( args.length == 1 ) serverPort = Integer.parseInt(args[0]);
try {
// instantiates a stream socket for accepting
// connections
ServerSocket myConnectionSocket = new ServerSocket(serverPort);
/**/System.out.println("Daytime server ready.");
while( true ) { // forever loop
// wait to accept a connection
/**/System.out.println("Waiting for a connection.");
MyStreamSocket myDataSocket = new MyStreamSocket(
myConnectionSocket.accept());
/**/System.out.println("connection accepted");
boolean done = false;
while( !done ) {
message = myDataSocket.receiveMessage();
/**/System.out.println("message received: " + message);
if( (message.trim()).equals("400") ) {
// Session over; close the data socket.
myDataSocket.sendMessage(logoutMessage);
myDataSocket.close();
done = true;
} // end if
if( (message.trim()).equals("100") ) {
// Login
/**/myDataSocket.sendMessage(loginMessage);
} // end if
if( (message.trim()).equals("200") ) {
File outFile = new File("C:\\OutFileServer.txt");
myDataSocket.receiveFile(outFile);
myDataSocket.sendMessage("File received "+outFile.length()+" bytes");
}
} // end while !done
} // end while forever
} // end try
catch (Exception ex) {
ex.printStackTrace();
}
} // end main
} // end class
Then the StreamSocket class:
public class MyStreamSocket {
private Socket socket;
private DataInputStream input;
private DataOutputStream output;
MyStreamSocket(InetAddress acceptorHost, int acceptorPort)
throws SocketException, IOException {
socket = new Socket(acceptorHost, acceptorPort);
setStreams();
}
MyStreamSocket(Socket socket) throws IOException {
this.socket = socket;
setStreams();
}
private void setStreams() throws IOException {
// get an input stream for reading from the data socket
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
}
public void sendMessage(String message) throws IOException {
output.writeUTF(message);
output.flush();
} // end sendMessage
public String receiveMessage() throws IOException {
String message = input.readUTF();
return message;
} // end receiveMessage
public void close() throws IOException {
socket.close();
}
public void sendFile(File file) throws IOException {
FileInputStream fileIn = new FileInputStream(file);
byte[] buf = new byte[Short.MAX_VALUE];
int bytesRead;
while( (bytesRead = fileIn.read(buf)) != -1 ) {
output.writeShort(bytesRead);
output.write(buf,0,bytesRead);
}
output.writeShort(-1);
fileIn.close();
}
public void receiveFile(File file) throws IOException {
FileOutputStream fileOut = new FileOutputStream(file);
byte[] buf = new byte[Short.MAX_VALUE];
int bytesSent;
while( (bytesSent = input.readShort()) != -1 ) {
input.readFully(buf,0,bytesSent);
fileOut.write(buf,0,bytesSent);
}
fileOut.close();
}
} // end class
Ditch the "helper" class. It is not helping you.