I want to create a program that checks ip address continuously.
i have a code that checks ip address and port, like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace WinNetworkIOCS {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void ConnectButton_Click(object sender, EventArgs e) {
DisableFields();
DoNetworkingConnection();
}
private void DisableFields() {
PortBox.Enabled = false;
IPAddressBox.Enabled = false;
SendMessageBox.Enabled = false;
ConnectButton.Enabled = false;
}
private void EnableFields() {
PortBox.Enabled = true;
IPAddressBox.Enabled = true;
SendMessageBox.Enabled = true;
ConnectButton.Enabled = true;
}
private void WriteToStatusBar(string Message) {
//EnableFields();
ThreadHelperClass.SetText(this, lblStatus, Message);
}
private void DoNetworkingConnection() {
Thread MyThread = null;
try {
ThreadStart ThreadMethod = new ThreadStart(ConnectTo);
MyThread = new Thread(ThreadMethod);
} catch (Exception e) {
WriteToStatusBar("Failed to create thread with error: " + e.Message);
return;
}
try {
MyThread.Start();
} catch (Exception e) {
WriteToStatusBar("The thread failed to start with error: " + e.Message);
}
}
private void ConnectTo() {
string ServerName = this.IPAddressBox.Text;
int Port = System.Convert.ToInt32(this.PortBox.Text);
WriteToStatusBar("IP Address: " + ServerName + "Port: " + Port);
Socket ClientSocket = null;
try {
// Let's connect to a listening server
try {
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
WriteToStatusBar("Socket is OK...");
} catch (Exception e) {
throw new Exception("Failed to create client Socket: " + e.Message);
}
IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse(ServerName), Convert.ToInt16(Port));
try {
ClientSocket.Connect(ServerEndPoint);
WriteToStatusBar("Connect() is OK...");
} catch (Exception e) {
throw new Exception("Failed to connect client Socket: " + e.Message);
}
} catch (Exception e) {
WriteToStatusBar(e.Message);
ClientSocket.Close();
return;
}
// Let's create a network stream to communicate over the connected Socket.
NetworkStream ClientNetworkStream = null;
try {
try {
// Setup a network stream on the client Socket
ClientNetworkStream = new NetworkStream(ClientSocket, true);
WriteToStatusBar("Instantiating NetworkStream...");
} catch (Exception e) {
// We have to close the client socket here because the network
// stream did not take ownership of the socket.
ClientSocket.Close();
throw new Exception("Failed to create a NetworkStream with error: " + e.Message);
}
StreamWriter ClientNetworkStreamWriter = null;
try {
// Setup a Stream Writer
ClientNetworkStreamWriter = new StreamWriter(ClientNetworkStream);
WriteToStatusBar("Setting up StreamWriter...");
} catch (Exception e) {
ClientNetworkStream.Close();
throw new Exception("Failed to create a StreamWriter with error: " + e.Message);
}
try {
ClientNetworkStreamWriter.Write(this.SendMessageBox.Text.ToString());
ClientNetworkStreamWriter.Flush();
WriteToStatusBar("We wrote " + this.SendMessageBox.Text.Length.ToString() + " character(s) to the server.");
} catch (Exception e) {
throw new Exception("Failed to write to client NetworkStream with error: " + e.Message);
}
} catch (Exception e) {
WriteToStatusBar(e.Message);
} finally {
// Close the network stream once everything is done
ClientNetworkStream.Close();
}
}
delegate void SetTextCallback(string text);
}
Problem is that it does not check the ip address and port continuously.
What to add into my code to make this happen?
I am assuming that what you mean is that you wish to be able to run your program more than once, not that you wish for it to check over and over again and therefore that your problem is in fact that your program finishes the task of pinging but then never allows you to enter new information?
This is because in your function
private void ConnectButton_Click(object sender, EventArgs e) {
DisableFields();
DoNetworkingConnection();
}
You run the function DisableFields(); and DoNetworkingConnection(); Assuming that the DoNeworkingConnection(); works and it runs the code once then your problem is that you never enable your controls again since in
private void WriteToStatusBar(string Message) {
//EnableFields();
ThreadHelperClass.SetText(this, lblStatus, Message);
}
You have commented out EnableFields(); that re-enables your controls. If this is not the case and you are actually trying to make it run continuously you would have to wrap the sending part of the ConnectTo() in a while loop
while(true)
{
ClientNetworkStreamWriter.Write(this.SendMessageBox.Text.ToString());
ClientNetworkStreamWriter.Flush();
WriteToStatusBar("We wrote " + this.SendMessageBox.Text.Length.ToString() + " character(s) to the server.");
}
Though if this is the case please state what you are trying to achieve and you will probably get a better solution because this will quickly turn into something like a DOS attack..
Related
I have client like this :
import org.basex.api.client.ClientSession;
#Slf4j
#Component(value = "baseXAircrewClient")
#DependsOn(value = "baseXAircrewServer")
public class BaseXAircrewClient {
#Value("${basex.server.host}")
private String basexServerHost;
#Value("${basex.server.port}")
private int basexServerPort;
#Value("${basex.admin.password}")
private String basexAdminPassword;
#Getter
private ClientSession session;
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
this.session = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
}
}
It is a singleton injected in a service which run mulitple queries like this :
Query query = client.getSession().query(finalQuery);
return query.execute();
All threads query and share the same session.
With a single thread all is fine but with multiple thread I get some random (and weird) error, like the result of a query to as a result of another.
I feel that I should put a synchronized(){} arround query.execute() or open and close session for each query, or create a pool of session.
But I don't find any documentation how the use the session in parrallel.
Is this implementation fine for multithreading (and my issue is comming from something else) or should I do it differently ?
I ended creating a simple pool by adding removing the client from a ArrayBlockingQueue and it is working nicely :
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
final int poolSize = 5;
this.resources = new ArrayBlockingQueue < ClientSession > (poolSize) {
{
for (int i = 0; i < poolSize; i++) {
add(initClient());
}
}
};
}
private ClientSession initClient() throws IOException {
ClientSession clientSession = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
return clientSession;
}
public Query query(String finalQuery) throws IOException {
ClientSession clientSession = null;
try {
clientSession = resources.take();
Query result = clientSession.query(finalQuery);
return result;
} catch (InterruptedException e) {
log.error("Error during query execution: " + e.getMessage(), e);
} finally {
if (clientSession != null) {
try {
resources.put(clientSession);
} catch (InterruptedException e) {
log.error("Error adding to pool : " + e.getMessage(), e);
}
}
}
return null;
}
Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
I'm working on a bluetooth-capable application, based on the well-known BluetoothChat example.
Basically with this app a client can send some packets to a server.
I have tested the application using two Xperia smartphones (Xperia X8 and Xperia Sola, android 2.1 and 4.0) and all is working fine: they both can act as client or server.
Unfortunately if I use an HTC Desire (android 2.3) as server, it won't be able to accept incoming connection from one of the Xperia client. It seems that the client connect() returns as if all was fine, but instead the server is blocked on its accept() as if nothing was happened.
Relevant code snippets:
1. "Accept Thread"
private class BluetoothAcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public BluetoothAcceptThread()
{
BluetoothServerSocket tmpSocket = null;
try
{
Method m = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] {int.class});
tmpSocket = (BluetoothServerSocket) m.invoke(bluetoothAdapter, APP_BT_CHANNEL);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread listen() (with reflection) failed", e);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
serverSocket = tmpSocket;
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread ServerSocket created");
}
#Override
public void run()
{
BluetoothSocket socket = null;
try
{
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread calling accept()...");
socket = serverSocket.accept();
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread accept() returned");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread accept() failed: " + e.getMessage());
}
if (socket != null)
{
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread accept() successfully");
synchronized (BluetoothManager.this)
{
if (currentState == SocketState.LISTENING || currentState == SocketState.CONNECTING)
startBluetoothConnection(socket); // all is ok, it can proceed
else if (currentState == SocketState.INACTIVE || currentState == SocketState.CONNECTED)
cancel(socket);
}
}
}
#Override
public void cancel()
{
try
{
serverSocket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread ServerSocket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread close() failed", e);
}
}
private void cancel(BluetoothSocket newSocket)
{
try
{
newSocket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread client socket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread client socket close() failed", e);
}
}
}
2. "Connect thread"
private class BluetoothConnectThread extends Thread
{
private final BluetoothSocket socket;
private final BluetoothDevice device;
public BluetoothConnectThread(BluetoothDevice d)
{
device = d;
BluetoothSocket tmpSocket = null;
try
{
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmpSocket = (BluetoothSocket) m.invoke(device, APP_BT_CHANNEL);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothConnectThread create() (with reflection) failed", e);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
socket = tmpSocket;
Log.d(MainActivity.DEBUG_TAG, "BluetoothConnectThread client socket created");
}
#Override
public void run()
{
stopBluetoothDiscovery(); // otherwise it will slow down the connection
try
{
socket.connect();
Log.d(MainActivity.DEBUG_TAG, "BluetoothConnectThread connect() successfully");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothConnectThread connect() failed", e);
String deviceName = device != null ? device.getName() : "none";
connectionFailed(deviceName); // notify UI thread
return;
}
synchronized (BluetoothManager.this)
{
bluetoothConnectThread = null;
}
startBluetoothConnection(socket); // create the "Communication" Thread
}
#Override
public void cancel()
{
try
{
socket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothConnectThread client socket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothConnectThread close() failed", e);
}
}
}
3. "Communication Thread" (aka ConnectedThread in BluetoothChat sample)
private class BluetoothCommunicationThread extends Thread
{
private final BluetoothSocket socket;
private final InputStream inputStream;
private final OutputStream outputStream;
public BluetoothCommunicationThread(BluetoothSocket s)
{
socket = s;
InputStream in = null;
OutputStream out = null;
try
{
in = socket.getInputStream();
out = socket.getOutputStream();
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread failed to get streams", e);
}
inputStream = in;
outputStream = out;
}
#Override
public void run()
{
byte[] buffer = new byte[BT_BUFF_SIZE];
int readBytes;
while (true)
{
try
{
readBytes = inputStream.read(buffer, 0, buffer.length);
if (readBytes != -1)
{
Message message = messageHandler.obtainMessage(DATA_MSG, readBytes, -1, buffer);
message.sendToTarget(); // notify to UI thread the bytes counter
}
else
{
BluetoothDevice device = socket.getRemoteDevice();
String deviceName = device != null ? device.getName() : "none";
connectionLost(deviceName);
break;
}
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread read() failed", e);
BluetoothDevice device = socket.getRemoteDevice();
String deviceName = device != null ? device.getName() : "none";
connectionLost(deviceName);
break;
}
}
}
public void write(byte[] buffer)
{
try
{
outputStream.write(buffer);
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread write() failed", e);
}
}
#Override
public void cancel()
{
try
{
socket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothCommunicationThread socket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread close() failed", e);
}
}
}
So the steps of the problem are the following:
HTC Desire server calls accept()
Xperia client calls connect()
The connect returns as if the connection was established
Nothing is happening on the HTC, always blocked on accept()
Xperia client thinks that it's connected, so it creates the CommunicationThread and calls the blocking read(); this function throws java.io.IOException: Software caused connection abort, probably because the socket is not connected.
Finally these are the relevant logcats:
Xperia client:
09-20 00:44:23.562 9106-9106/com.powertester D/[PowerTester Debug]﹕ BluetoothConnectThread client socket created
09-20 00:44:25.704 9106-9579/com.powertester D/[PowerTester Debug]﹕ BluetoothConnectThread connect() successfully
09-20 00:44:25.734 9106-9579/com.powertester D/[PowerTester Debug]﹕ BluetoothCommunicationThread started and I/O streams ready
09-20 00:44:25.764 9106-9589/com.powertester E/[PowerTester Error]﹕ BluetoothCommunicationThread read() failed
java.io.IOException: Software caused connection abort
at android.bluetooth.BluetoothSocket.readNative(Native Method)
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:333)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at com.powertester.net.BluetoothManager$BluetoothCommunicationThread.run(BluetoothManager.java:518)
09-20 00:44:25.844 9106-9106/com.powertester D/[PowerTester Debug]﹕ BluetoothCommunicationThread socket closed
HTC server:
09-19 15:47:07.591 2422-2422/com.powertester D/[PowerTester Debug]﹕ BluetoothAcceptThread ServerSocket created
09-19 15:47:07.591 2422-2484/com.powertester D/[PowerTester Debug]﹕ BluetoothAcceptThread calling accept()...
The really strange thing is that the HTC Desire works if used as client with one of the Xperia used as server.
So, is a problem of my app or a problem in the HTC Desire bluetooth stack?
After some troubles I have realized that the problem is the reflection itself and the explicit use of a Bluetooth Channel.
Using the normal way (i.e. the not-hidden bluetooth methods) my app works perfectly.
I have searched for the solution but couldn't make it work. Here is the summary. I am trying to implement a webservice which runs on Glassfish 2.1 that implements a synchronous JMS Request-Response using Temporary queue. It sends a message to another Glassfish application running on remote server. I am able to send the message and process it but when the final message is sent back to temporary queue, the webservice gets the response as null. Here is the code:
private Message requestReply(String msg, Queue jmsRequestResponse, ConnectionFactory jmsRequestRespConnFactory) {
javax.jms.Connection conn = null;
javax.jms.MessageConsumer consumer = null;
javax.jms.Message replyMsg = null;
javax.jms.Session sess = null;
try {
logger.debug("[requestreply input message[" + msg);
conn = jmsRequestRespConnFactory.createConnection();
conn.start();
sess = conn.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
javax.jms.Message reqMessage = sess.createTextMessage(msg);
javax.jms.Destination replyDestination = (jmsRequestResponse instanceof javax.jms.Queue) ? sess.createTemporaryQueue() : sess.createTemporaryTopic();
reqMessage.setJMSReplyTo(replyDestination);
sess.createProducer(jmsRequestResponse).send(reqMessage);
replyMsg = consumer.receive(60000);
consumer.close();
sess.close();
conn.close();
} catch (JMSException ex) {
logger.debug("exception in requestreply");
} finally {
if (consumer != null) {
try {
consumer.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return replyMsg;
}
what am I missing here?? When I print the replyMsg, it is always null.
I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.