The code below triggers the following error:
Error: Exception when sending command: Socket closed
public synchronized void sendCommand(final ServerCommand pServerCommand) {
if (pServerCommand == null) {
return;
}
try {
//byte array to write server command
ByteArrayOutputStream baosData = new ByteArrayOutputStream();
DataOutputStream osData = new DataOutputStream(baosData);
//byte array that will be used to write on socket
//this will contain length of ByteArrayData and then ByteArrayData
ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
DataOutputStream osOut = new DataOutputStream(baosOut);
//write command into osData byte array
pServerCommand.write(osData);
//write length of command into main byte array
osOut.writeShort(baosData.size());
//write command into main byte array
baosData.writeTo(baosOut);
OutputStream out = this.getSocket()
.getOutputStream();
//write main byte array on socket
byte[] data = baosOut.toByteArray();
out.write(data, 0, data.length);
out.flush();
} catch (IOException e) {
Log.pt("Exception when sending command", e.getMessage());
// Socket is possibly closed
}
}
For whatever reason, the socket to which you are writing is closed. Either it was not opened, it was closed already on your end, or it was closed on the other end, apparently a server.
A couple of suggestions. First, move all the data prep code to a method that returns a byte[]. Socket code is hard enough without mixing it with code that manipulates data.
Second, make sure the socket was actually opened. That's not a given.
Related
This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 1 year ago.
I am try uploading the image using the below servlet
But after upload I am able save the file but I am not able to open I checked the file is corrupted.
Instead of using the annotation I have describe multipart-config in web.xml.
I this code I am trying to get the image file I send the data using AJAX.
Then I am redirected to Register servlet there I am using InputStream class to handle data.
After this I creating the file and upload this Inputdata to file in some directory on server.
public class Register extends HttpServlet{
#Override
protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
String email=req.getParameter("email");
Part part = req.getPart("image");
String filename = part.getSubmittedFileName();
InputStream is = req.getInputStream();
byte[] data = new byte[is.available()];
String path = "D:\\FullstackWeb\\images\\icon\\"+filename;
System.out.println(path);
FileOutputStream fos=new FileOutputStream(path);
fos.write(data);
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://dns1.nishchay.com:3306/register","demouser","123Nbr#");
String query = "Insert INTO register.signup(username,email,userpassword,filename) values(? ,?, ?,?)";
PreparedStatement pstmt= conn.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, email);
pstmt.setString(3, password);
pstmt.setString(4, path);
pstmt.executeUpdate();
conn.close();
}catch(Exception e) {
out.println("<h1>Issue is occured</h1>");
}
}
}```
You are not reading in the image data:
InputStream is = req.getInputStream();
byte[] data = new byte[is.available()];
String path = "D:\\FullstackWeb\\images\\icon\\"+filename;
System.out.println(path);
FileOutputStream fos=new FileOutputStream(path);
fos.write(data);
does not contain any is.read() call and it doesn't close the FileOutputStream.
In addition to that your allocated buffer is to small for most images. The JavaDoc for InputStream.available() states
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking
To completely read the image data you could simply replace the above code with
Files.copy(is, Paths.get("D:\\FullstackWeb\\images\\icon\\"+filename));
but with a big caveat: since the file name is supplied by the user of your service this opens your code to security problems.
I am replacing an old java application with an electron app. In the old application, we opened the cash drawer of a cash register by printing a byte array with a DocFlavor DocFlavor.BYTE_ARRAY.AUTOSENSE
Is it possible to do the same thing with an npm package?
// Cash Drawer
byte[] CD_KICK_2 = {0x1b,0x70,0x00}; // Sends a pulse to pin 2 []
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = service.createPrintJob();
try {
Doc doc = new SimpleDoc(CD_KICK_2, flavor, null);
job.print(doc, null);
} catch (Exception e) {
e.printStackTrace();
}
Below are different code I have used but I need to execute ETL or batch file gave link to button dashbord via view page but I couldn't execute or run file
please suggest me on same
public ActionResult RunETL(){
try
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo(#"D:\Jobs\Execute");
p.Start();
//Process p = new Process();
//// Redirect the output stream of the child process.
//p.StartInfo.UseShellExecute = false;
//p.StartInfo.RedirectStandardOutput = true;
////p.StartInfo.FileName = #"D:\Jobs\Execute";
//p.Start();
//// Do not wait for the child process to exit before
//// reading to the end of its redirected stream.
//p.WaitForExit();
//// Read the output stream first and then wait.
//string output = p.StandardOutput.ReadToEnd();
//p.WaitForExit();
//Response.Write("Done");
////ViewBag.Result = "ETL Running";
}
catch (Exception ex)
{
//ViewBag.Result = ex.Message;
}
return RedirectToAction("Home");
}
have a Look at the Application Pool Identity that's used to run your web app.
it should have a Execute Right on the location of the batch file.
I have application client(javascript)-server(golang) and the connection between them are all over websocket. I'm planing using binary messages and i want to create my own protocol for messaging like in this page protocol.
I'm already figure it out in javascript by using DataView but not in golang. Event the primitive data type are similar like they have int8, uint8, int16, uint16 etc, i can't figure it out.
This is the message frame:
1 Uint8 opcode
2 Uint16 msg
This is the example of javascript code handling the incoming message form websocket with message frame above:
websocket.onmessage = function(evt) {
var data = new DataView(evt.data);
var opcode = data.getUint8(0);
var msg = data.getUint16(1);
}
Can you show me how to do it in golang? i'm using gorilla websocket. I know that read message are in []byte, but i don't know how to slice it like javascript does with DataView.
Thanks
For the uint16 you'll need the binary package. Double-check if LittleEndian is what you want.
package main
import (
"encoding/binary"
)
func main() {
a := []byte("yak")
/* opcode */ _ = uint8(a[0])
/* message */ _ = binary.LittleEndian.Uint16(a[1:3])
}
https://play.golang.org/p/HRu7C5h2a5
I have SocketServer on Java with opened Socket and data, that sends on telnet-like way: when I open this socket in Chrome (localhost:9999 e.g.) some events repeatedly displayed.
So the question is: how can I parse this data using JS on single html page? I want to add some charts after parsing this data.
I've tryed to use WebSocket("ws://localhost:9999") but get only "invalid status line" error on WebSocket handshake.
P.S. Sorry for my bad English
UPD: This is an example of implementation of my SocketServer on Java: (no special code for WebSocket)
public class Main {
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(9999);
Socket sock = ssock.accept();
ssock.close();
PrintStream pstream = new PrintStream(sock.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i);
}
pstream.close();
sock.close();
}
}
I need to trace this PrintStream on a webpage using JS.