Android socket client slow - sockets

I am trying to make a faster socket client to send RGB colors each time, the faster call should be from 1 to 10 times per second.
I am using this code:
try {
socket = new Socket("192.168.0.9",1234);
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//toServer = new BufferedWriter(new PrintWriter(socket.getOutputStream(),true));
//out = new PrintWriter(new BufferedWriter(
// new OutputStreamWriter(socket.getOutputStream())), false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e1) {
Log.e("Error", "Error");
e1.printStackTrace();
} catch (IOException e1) {
Log.e("Error", "Error");
e1.printStackTrace();
}
And each time I am changing color from the picker, I am calling this method
dataOutputStream.writeUTF(";"+red+";"+green+";"+blue+";"+brightness+";");
I have tried a script in python that does the same, 100 times in 2 seconds and I dont have any lags.
What I am getting, is that the python server is waiting for new requests but Android takes time to send them through the socket connection.
I actually tried 3 different method to instance the output write, but only with the DataOutputStream is faster enough but still have some lag.
What is the best approach to fix this issue?

Put a BufferedOutputStream between the DataOutputStream and the socket, and flush the DOS after each writeUTF(). At the peer, use a DataInputStream over a BufferedInputStream.

Related

Jmeter - Force close a socket/wait until message recieved

I am opening a socket in jmeter (using groovy in JSR223 Sampler), and storing the message in a jmeter variable. This is the below code:
SocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getByName("localhost"),4801);
def server = new ServerSocket()
server.bind(inetSocketAddress)
while(!vars.get("caseId"))) {
server.accept { socket ->
log.info('Someone is connected')
socket.withStreams { input, output ->
InputStreamReader isReader = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
String finalStr = sb.toString()
String caseId = finalStr.split("<caseId>")[1].split("</caseId>")[0]
vars.put("caseId", caseId)
}
log.info("Connection processed")
}
}
if(vars.get("caseId"))
{
try
{
server.close();
vars.put("socketClose",true);
}
catch(Exception e)
{
log.info("Error in closing the socket: " + e.getMessage());
}
}
Now, there is some time delay between the first loop is executed and the message being recieved from the port. It doesnt receive the message immediately, and hence while loop is executed again. And then message is received and it sets caseId. It goes on to close the socket, because caseId is set. And that is throwing the error, because socket is still waiting for the message. So is there a way, to wait until socket has recieved all the messages, so i could properly close it?
Or just force close the socket, and Jmeter wont throw any exception?
Or when i execute next component, say IF controller in Jmeter, it waits until variable socketClose is set true? In that way, instead of while loops inside JSR223 sampler, i could use multiple If Controllers in Jmeter thread.
This is how ServerSocket.close() function works
public void close()
throws IOException
Closes this socket. Any thread currently blocked in accept() will throw a SocketException.
I don't think there is a way "to wait until socket has recieved all the messages" because Socket is dump as a rock and it can either listen for connections or shut down.
Maybe you might be interested in setSoTimeout() function?
Also this line:
vars.put("socketClose",true)
is very suspicious, I think you need to change it either to:
vars.put("socketClose", "true")
or to
vars.putObject("socketClose",true)
as JMeterVariables.put() function can accept only a String, see Top 8 JMeter Java Classes You Should Be Using with Groovy article for more details.

Can’t write amount of data to kepware

When I write data to kepware server by milo, sometimes some data can not be written successfully. But the server returned
StatusCode{name=Good, value=0x00000000, quality=good}
The server did not display the data which I had written.
Thanks in advance for any help
Single thread did not work.
Create new client when start to write data.
There is only one client which responds to writing.
All of these failed.
mWriteClient = new OPCUAClientRunner(KSOPCUASubscription.this).createClient();
mWriteClient.connect().get();
} catch (Exception e) {
e.printStackTrace();
logger.error("OPCUAClient connect Exception", e);
return ;
}
logger.info("Wrote identifier: " + identifier);
List<NodeId> nodeIds = ImmutableList.of(new NodeId(namespaceIndex, identifier));//Int32"t|bbb"
Variant v = new Variant(value);
// don't write status or timestamps
DataValue dv = new DataValue(v, null, null);
logger.info("OPCUAClient begin write");
// write asynchronously....
CompletableFuture<List<StatusCode>> f =
mWriteClient.writeValues(nodeIds, ImmutableList.of(dv));
// ...but block for the results so we write in order
List<StatusCode> statusCodes = null;
try {
statusCodes = f.get();
} catch (InterruptedException e) {
e.printStackTrace();
logger.error("OPCUAClient write get response Exception", e);
} catch (ExecutionException e) {
e.printStackTrace();
logger.error("OPCUAClient write get response Exception", e);
}
StatusCode status = statusCodes.get(0);
logger.info("Wrote status: " + status.toString());
if (status.isGood()) {
logger.info("Wrote '{}' to nodeId={}", v, nodeIds.get(0));
}
Unless you're not actually writing the value you claim to be writing, a StatusCode of Good from the server means you're not doing anything wrong on the client side.
Maybe you can capture the exchange with Wireshark to further prove the issue is on the server side.

Multiple exception catch block java 8 eclipse

I'm getting an unhandled message exception for IOException. As you can see in the pasted code I've handled the IOException. The JDK for both eclipse & the project is Java 8 update 121 so I know catching multiple exceptions is supported. What am I doing wrong?
try (InputStream inputStream = BatchMessageProperties.class.getClassLoader().
getResourceAsStream(propertiesFileName)) {
load(inputStream);
//need to make sure all properties are present & not null.
validate(this);
} catch (IOException | InvalidBatchMessagePropertiesFileException ex) {
logger.error(ex.getLocalizedMessage());
ex.printStackTrace();
throw ex;
}
You do rethrow ex inside your catch block, which may be an IOException, right?

Class MessagingException not working as I think it should

I'm developing a web application that sends an email and has to check, that, in fact this mail has been delivered from my application side as much as possible in few seconds (I don't think you can do more than getting that the email has been delivered to email server, if that email server later cannot later send that email to the user that uses it because it has its inbox full or another situation like this, I think it cannot be helped, although if there's some way I'd like to know about it).
Anyway one thing I think could be checked without problems is if the email address doesn't exist as that gives an inmediate response, according to what I've read this could be done with class MessageException, but I've the following code:
String email=Utils.parseString(req,"email");
[....]
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
Session s = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(s);
try {
InternetAddress from = new InternetAddress(emailadressthatworks);
message.setFrom(from);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
try {
InternetAddress to = new InternetAddress(email);
message.addRecipient(Message.RecipientType.TO, to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
try {
message.setSubject("Subject");
message.setText("message");
Transport.send(message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
resp.sendRedirect("webpage.jsp");
return;
}
[....]
And whatever random String I asign to email it never throws an MessagingException in Transport.send(message); so I can redirect it to another jsp web page when I think it should according to what I have read.
Might I be missing something or is it that this class cannot detect that things?
Thanks for your help.
Use the strict InternetAddress constructor and call message.saveChanges() to perform the validation. See
Content-Type syntax check throws exception too late for more details.
See this JavaMail FAQ entry.
Also, it's up to your mail server whether it tries to detect some kinds of errors immediately or whether it queues all requests and only checks for errors later.

ADO.NET and Disposing without Using

I have a project that isn't using USING anywhere with their ADO.NET code. I am cleaning up their unclosed connections. Is the below code a best practice with try/catch/finally. I also have some that contains SqlTransaction that I'm disposing in between the command and connection dispose.
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
try
{
con.Open();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
con.Dispose();
}
Actually, there is no need to worry about closing the connection when using the SqlDataAdapter.Fill(dataset) method. This method closes the connection after performing every Fill.
Also, there is no need to call SqlCommand.Dispose() since the command itself has no unmanaged resources to clean up. What you should be concerned about is if SqlConnection.Close() is called at some point. This is done after Fill.
What you have is fine. It is always a good idea to dispose of objects that use unmanaged resources. However, if you get sick of always explicitly calling Dispose, the best practice is probably to use the using:
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString()))
{
using (SqlCommand cmd = new SqlCommand())
{
DataSet ds = new DataSet();
try
{
con.Open();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
catch (Exception ex)
{
throw; // I changed this too!
}
}
}
Also, you almost always want to simply throw if you're going to "rethrow" an exception. You lose some of your stack trace if you throw ex;.
The best practice is using using instead of try/finally :)
However in your case even using is not needed, because Fill() closes the connection:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyNGConnectDashBoardConnectionString"].ToString())
SqlDataAdapter da = new SqlDataAdapter("your sql is here", con);
da.Fill(ds);
Also simple re-throwing exceptions makes no sense at all. If you need to log error, just use plain throw; as #Cory suggested.