I want to send an image from java websocket server to HTML5 page. When I try to send String client received correct information, but when I want to send image in byteArray i get error:
"WebSocket connection to 'ws://127.0.0.1:9000/' failed: Unrecognized frame opcode: 15"
My server code:
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
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.net.ServerSocket;
import java.net.Socket;
import java.security.MessageDigest;
import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
public class WebSocket {
private ServerSocket server;
private Socket sock;
private InputStream in;
private OutputStream out;
public WebSocket() {
}
public void listen(int port) throws IOException {
server = new ServerSocket(port);
sock = server.accept();
server.close();
in = sock.getInputStream();
out = sock.getOutputStream();
}
private void handshake() throws Exception {
BufferedReader br = new BufferedReader(
new InputStreamReader(in, "UTF8"));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "UTF8"));
// the first line of HTTP headers
String line = br.readLine();
if (!line.startsWith("GET"))
throw new IOException("Wrong header: " + line);
// we read header fields
String key = null;
// read line by line until we get empty line
while (!(line = br.readLine()).isEmpty()) {
if (line.toLowerCase().contains("sec-websocket-key")) {
key = line.substring(line.indexOf(":") + 1).trim();
}
}
if (key == null)
throw new IOException("No Websocket key specified");
System.out.println(key);
// add key and magic value
String accept = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// sha1
byte[] digest = MessageDigest.getInstance("SHA-1").digest(
accept.getBytes("UTF8"));
// and base64
accept = DatatypeConverter.printBase64Binary(digest);
// send http headers
pw.println("HTTP/1.1 101 Switching Protocols");
pw.println("Upgrade: websocket");
pw.println("Connection: Upgrade");
pw.println("Sec-WebSocket-Accept: " + accept);
pw.println();
pw.flush();
}
private void send(String message) throws Exception {
BufferedImage image = ImageIO.read(new File("image.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] byteArray = baos.toByteArray();
out.write(byteArray);
out.flush();
}
private void close() {
try {
sock.close();
} catch (IOException e) {
System.err.println(e);
}
}
/** throws Exception, because we don't really care much in this example */
public static void main(String[] args) throws Exception {
WebSocket ws = new WebSocket();
System.out.println("Listening...");
ws.listen(9000);
System.out.println("Handshake");
ws.handshake();
System.out.println("Handshake complete!");
ws.send("I got your message! It's length was");
ws.close();
}
}
and my page in html:
<!DOCTYPE HTML>
<html>
<body>
<button onclick="webs()">WebSocket message</button>
<script>
function webs() {
var ws = new WebSocket("ws://127.0.0.1:9000");
ws.onopen = function(){
console.log("Opened!");
};
ws.onmessage = function(evt){
console.log("Received!");
};
ws.onclose = function(ev){
console.log("Closing connection");
};
ws.onerror = function(ev){
console.log("Connection error: " + ev.reason);
};
}
</script>
</body>
</html>
I quess it is something wrong with this handshake and http headers but I have no idead what.
i think u miss "\r\n" at the end of each line
check this
http://en.wikipedia.org/wiki/WebSocket
hope this helps ..
Related
server class :
the program is about to receive data from client and then reply. the server is okay..., but the problem is when the server send the reply to the client. the client always says 'the socket is close'. i try to delete secket close statement but the result is same.., the output says that 'the socket is close'. so please help me to solve this problem...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
public class Nomor3Server {
public static final int SERVICE_PORT = 2020;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(SERVICE_PORT);
System.out.println("DAytime service started");
for (;;) {
Socket nextClient = server.accept();
BufferedReader pesan = new BufferedReader(new InputStreamReader(nextClient.getInputStream()));
String messageIn = pesan.readLine();
System.out.println("Received request from "
+ nextClient.getInetAddress() + " : "
+ nextClient.getPort()
+ "\nIsi Pesan : " + messageIn);
String messageOut = "انا لا ادر";
switch (messageIn) {
case "saya":
messageOut = "أنا";
break;
case "kamu":
messageOut = "أنت";
break;
default:
break;
}
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(messageOut);
out.flush();
out.close();
System.out.println("Message sent");
//nextClient.close();
}
} catch (BindException e) {
System.err.println("Server Already Running on port : " + SERVICE_PORT);
} catch (IOException ioe) {
System.err.println("error : " + ioe);
}
}
}
client class :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
public class Nomor3Client {
public static final int SERVICE_PORT = 2020;
public static void main(String[] args) {
try {
String hostname = "localhost";
System.out.println("Connection Established");
//for (;;) {
System.out.println("Enter Your Message : ");
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String pesan = read.readLine();
Socket daytime = new Socket(hostname, SERVICE_PORT);
if (pesan.equals("exit")) {
System.exit(0);
} else {
daytime.setSoTimeout(2000);
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close();
BufferedReader messageIn = new BufferedReader(new InputStreamReader(daytime.getInputStream()));
System.out.println("Respond : " + messageIn.readLine());
System.out.println("diterima");
}
daytime.close();
//}
} catch (IOException e) {
System.err.println("Error : " + e);
}
}
}
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close();
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#getOutputStream()
Closing the returned OutputStream will close the associated socket.
Socket get closed in such situations:
when you close the socket,
when you close the input or the output socket stream,
when you close the object, which is directly or indirectly wrapping the input or the output socket stream, e.g. BufferedReader or Scanner.
Server Class
OutputStream out = nextClient.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(messageOut);
out.flush();
out.close(); //Don't close this
Client Code :
OutputStream out = daytime.getOutputStream();
PrintStream pout = new PrintStream(out);
pout.print(pesan);
out.flush();
out.close(); //Don't close this
I'm trying to connect a java application to the json api of betaface.
I ran into a weird problem I hope you guys can help me with.
I have the (ugly) code to connect to the api. This code is just to test what kind of responses I get and what to do with it.
I build a request body, print the request body to the console, and then write the request body to the api. The problem is that the responsecode is 400.
The weird thing is, when I copy the request body and execute it through Advanced Rest Client it will return a 200 and the expected body. I think the problem is not in the body but somewhere in the HTTPUrlConnection.
I've added my test class to illustrate the problem, you guys would only need a small image to reproduce the problem. The API keys are the free to use api keys of betaface.
Thank you very much for any help you can give me.
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import javax.imageio.ImageIO;
public class APITest {
/**
* #param args
*/
public static void main(String[] args) {
try
{
new APITest();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public APITest() throws MalformedURLException, IOException {
String api_key = "d45fd466-51e2-4701-8da8-04351c872236";
String api_secret = "171e8465-f548-401d-b63b-caf0dc28df5f";
String urlToConnect = "http://www.betafaceapi.com/service_json.svc/UploadNewImage_File";
File fileToUpload = new File("C:\\test.jpg");
byte[] t = getImageBase64ByteArray(fileToUpload);
String body = "";
body += "{\"api_key\":\"";
body += api_key;
body += "\",\"api_secret\":\"";
body += api_secret;
body += "\",\"detection_flags\":\"\",\"imagefile_data\":[";
for(int i = 0; i < t.length; i++) {
body += t[i];
if(i < t.length - 1)
body += ",";
}
body += "],\"original_filename\":\"Test.jpg\"}";
System.out.println(body);
HttpURLConnection connection = (HttpURLConnection)new URL(urlToConnect).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(body);
writer.newLine();
writer.flush();
writer.close();
int responseCode = connection.getResponseCode();
System.out.println(responseCode); // Should be 200
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null){
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
}else{
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String line;
while ((line = br.readLine()) != null){
response += line;
}
System.out.println(response);
}
public byte[] getImageBase64ByteArray(File file) {
BufferedImage bufferedImage;
try
{
bufferedImage = ImageIO.read(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoded = "";
try {
ImageIO.write(bufferedImage, "jpg", bos);
byte[] imageBytes = bos.toByteArray();
encoded = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return encoded.getBytes();
}
catch(IOException e)
{
e.printStackTrace();
}
return new byte[0];
}
}
I'm trying to develop a simple Java file transfer application using TCP.
My current server code is as follows:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
new FTPServer().go();
}
void go() {
try {
ServerSocket server = new ServerSocket(2015);
System.out.println("server is running ....!");
while (true) {
Socket socket = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String file = reader.readLine();
System.out.println("file to be downloaded is : " + file);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
//bos.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Using my current server code above, the downlloding does not work as expected. the above code sends part of the file to the client , not the entire file. Note that I used the flush method to flush the buffer. but when I replace the flush () method by the close () method, the file is fully sent to the client whithout any loss. Could anyone please explain this behavior!
UPDATE: Here is the code of my client:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* #author aaa
*/
public class FTPClient {
public static void main(String[] args) {
String file = "JasperReports-Ultimate-Guide-3.pdf";
try {
InetAddress address = InetAddress.getLocalHost();
Socket socket = new Socket(address, 2015);
System.out.println("connection successfully established ....!");
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println(file);
pw.flush();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy" + file));
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
System.out.println("file download is complete ...!");
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Another behavior without the use of Socket. take the following code that copy a file from a source to a destination:
public class CopieFile {
static void fastCopy(String source, String destination) {
try {
FileInputStream fis = new FileInputStream(source);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(destination);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) throws IOException {
String source = "...";
String destination = "...";
fastCopy(source, destination);
}// end main
}// end class
the above code to copy a file from one location to another without any loss. Note well that I did not close the stream.
If you never close the stream the client wil never get end of stream so it will never exit the read loop.
In any case the stream and the socket are about to go out of scope, so if you don't close them you have a resource leak.
I am trying to implement FTP protocol using socket programing in java. I am using the ObjectOutputStream to write the data requested to the socket in the server side but i am getting the following error on the console window..
Software caused connection abort: socket write error
Here is the implementation of my program
Server side:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
try {
#SuppressWarnings("resource")
ServerSocket ss = new ServerSocket(4550);
while(true) {
Socket socket = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
FileInstance file = new FileInstance();
System.out.println(file.srcDir = br.readLine());
System.out.println(file.destDir = br.readLine());
System.out.println(file.filename = file.srcDir.substring(file.srcDir.lastIndexOf("/") + 1));
File f = new File(file.srcDir);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
file.FILE_SIZE = bytes.length;
file.fileData = bytes;
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file);
System.out.println("Success");
oos.close();
fis.close();
br.close();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Client Side:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class FTPClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 4550);
BufferedReader sbr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the path of requested file");
String path = sbr.readLine();
System.out.println(path);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter Destination");
path = path + "\n" + sbr.readLine();
System.out.println(path);
pw.write(path);
pw.close();
sbr.close();
// receive file
ObjectInputStream ois= new ObjectInputStream(socket.getInputStream());
FileInstance file = (FileInstance)ois.readObject();
ois.close();
if(!new File(file.destDir).exists())
new File(file.destDir).mkdir();
File nfile = new File(file.destDir + "/" + file.filename);
FileOutputStream fos = new FileOutputStream(nfile);
fos.write(file.fileData);
fos.close();
socket.close();
System.out.println("Success");
} catch(IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
this is the FileInstance class......
import java.io.Serializable;
public class FileInstance implements Serializable {
private static final long serialVersionUID = 1L;
public String destDir;
public String srcDir;
public String filename;
public long FILE_SIZE;
public byte[] fileData;
public String status;
}
You have two problems in FTPClient
You are closing the socket prematurely. At line 22 pw.close() needs to be pw.flush()
Even after you fix the first issue the server will hang. You need to add a newline to the end of the path string you send so the server, using readLine(), can read entire lines; otherwise it waits forever for a complete line that never arrives.
This was trivial to debug in Eclipse. If you want to be a good developer, debugging skills are crucial. Set more than one breakpoint and see what happens. Experiment. Play. Learn.
I need to read an image file and send it to a web browser using HTTP protocol, and I cannot figure out how to send the bytes of the image. I cannot for the life of me figure it out. Thanks in advance. Here is my code:
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Main {
byte[] byt=null;
public String read(String message){
String httpHeader="";
String toReturn="";
try{
if(message!=null){
String[] parts=message.split("\n");
String[] RequstParts=parts[0].split(" ");
System.out.println("This is a "+RequstParts[0]+" request for "+RequstParts[1]);
if(RequstParts[1].equals("/"))RequstParts[1]="index.html";
if(RequstParts[0].equals("GET")){
if(RequstParts[1].endsWith(".html")){
httpHeader="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
BufferedReader in = new BufferedReader(new FileReader(new File("WebContent/"+RequstParts[1])));
String line="";
while(null!=(line=in.readLine())){
toReturn+=line;
}
}else if(RequstParts[1].endsWith(".jpg")){
httpHeader="HTTP/1.1 200 OK\r\nContent-Type: image/jpg\r\nContent-Length: 13312\r\n\r\n";
}
}
}
}catch(Exception e){
toReturn+="<br>ERROR: "+e.toString();
return httpHeader+toReturn;
}
return httpHeader+toReturn;
}
public Main(){
try{
ServerSocket listener = new ServerSocket(9090);
System.out.println("HTTP server started!");
while(true){
Socket socket = listener.accept();
System.out.println("\nRecieved Data!");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message=read(in.readLine());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("\nSENDING "+message);
out.println(message);
out.println(byt);
out.close();
}
}catch(Exception e){
System.out.println("ERROR "+e.toString());
e.printStackTrace();
}
}
public static void main(String args[]){
new Main();
}
}
This should work:
public byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
So call this extractBytes on an image (specified as a filename to the method here), and send the returned byte[] using:
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write(byte[]);
Method code taken from here.