I am trying to open input and output streams in android but I'm not sure how to go about this. I have opened a socket connection in J2ME previously by using the following in the server:
scn = (ServerSocketConnection) Connector.open("socket://:5000");
String myAddress = scn.getLocalAddress();
si.setText("My address: " + myAddress);
// Wait for a connection.
sc = (SocketConnection) scn.acceptAndOpen();
//Get address of socket connection
String yourAddress = sc.getAddress();
si.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();
Now I want to put this into android but its not letting me open input and output streams and also I had to change a few things which I'm not sure would work in the same way.
scn = (ServerSocket) Connector.open("socket://:5000");
String myAddress = scn.getLocalAddress();
Connection.setText("My address: " + myAddress);
// Wait for a connection.
Socket sc = scn.accept();
//Get address of socket connection
String yourAddress = sc.getAddress();
Connection.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();
The errors which I am getting in android are with the Connector, getLocalAddress, getAddress and openInput and OutputStreams.
I would appreciate any help on this, as I am having great difficulty setting this up in android.
Thanks
Edit:
I have changed the Android code to this:
ServerSocket scn = new ServerSocket(5554);
InetAddress myAddress = scn.getInetAddress();
Connection.setText("My address: " + myAddress);
// Wait for a connection.
Socket sc = scn.accept();
//Get address of socket connection
InetAddress yourAddress = sc.getInetAddress();
Connection.setText("Connected to: " + yourAddress);
is = sc.openInputStream();
os = sc.openOutputStream();
Which compiles fine but I get an error on:
is = sc.openInputStream();
os = sc.openOutputStream();
Is there another way to open input and output streams in android?
Thanks.
Related
I have a working SQL Server database on my laptop, a smart phone linked to the laptop by USB and wi-fi. I have the following code to connect to the database:
string connectionString = #"Data Source=192.168.1.102,1433;Initial Catalog=MyInsurance_database;Integrated Security=SSPI;Connection Timeout=15";
string databaseTable = "SurveyVariants";
string whereAnd = "5";
string selectQuery = String.Format("SELECT * FROM {0} WHERE RecNo = {1}", databaseTable, whereAnd);
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
//open connection
connection.Open();
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Connection = connection;
command.CommandText = selectQuery;
var result = command.ExecuteReader();
//check if account exists
var exists = result.HasRows;
Toast.MakeText(this, "Success - " + exists, ToastLength.Short).Show();
}
}
catch (Exception exception)
{
I know that the SQL string is correct and that in SSMS it returns one record correctly.
I have tried various permutations of Server= instead of Data Source=, Initial Catalog= instead of Database=, with and without the port number as 1433, 1434 or 80, after making a new rule for the firewall.
Error messages begin:
System.Data.SqlClient.SqlException (0x80131904): Snix_Connect (provider: SNI_PN7, error: 25 - SNI_ERROR_25)
Snix_Connect (provider: SNI_PN7, error: 25 - SNI_ERROR_25) ---> System.Net.Sockets.SocketException (0x80004005): The socket is not connected
at System.Data.SqlClient.SNI.SSRP.GetPortByInstanceName
etc.
or
System.Data.SqlClient.SqlException (0x80131904): Snix_Connect (provider: SNI_PN7, error: 40 - SNI_ERROR_40)
Snix_Connect (provider: SNI_PN7, error: 40 - SNI_ERROR_40)
etc.
What else can I try - any ideas? Thank you.
don't know why, the app when connecting to the SQL Server that is on the same network as the device, I can connect to it without any problems, but now I need to connect from the device over the internet to the SQL Server, isn't working, don't know why. I have a button to test the connection and it will call a method that contains this, the method is on background (AsyncTaskRunner)
try
{
String host, port, dbname, user, password, instance;
host = _editTextHost.getText().toString();
port = _editTextPort.getText().toString();
instance = _editTextInstance.getText().toString();
dbname = _editTextDbName.getText().toString();
user = _editTextUser.getText().toString();
password = _editTextPass.getText().toString();
String driver = "net.sourceforge.jtds.jdbc.Driver";
String conString;
if (TextUtils.isEmpty(port))
{
conString = "jdbc:jtds:sqlserver://" + host + ";databaseName=" + dbname + ";instance=" + instance;
}
else
{
conString = "jdbc:jtds:sqlserver://" + host + ":" + port + ";databaseName=" + dbname + ";instance=" + instance;
}
Connection con;
Class.forName(driver);
con = DriverManager.getConnection(conString, user, password);
con.close();
conSuccess = true;
}
catch (Exception e)
{
e.printStackTrace();
Log.e("SQLConfig", "Fail to connect");
Log.e("SQLConfig", e.toString());
Log.e("SQLConfig", e.getMessage());
}
return null;
When I do try to connect to the SQL Server on the same network works without any problems, but when I activate the 4g on the device I allways get the same error, that it can't find the instance. But if I connect to the server through the "SQL Server Management Studio" using the same information I can connect to the server without any problems.
I'm using the jtds driver, 1.3.1.
What could be doing this? Thanks
P.S. I all rdy have read some stuff about webservice, but I want to remove this option for now out of the picture
Edit 1: To clarify, I can connect to the server using the credentials on the version of Windows CE of the program or SQL Server Management Studio. When I put the outside IP and all the require information it connects to the server, it not connect on the Android only
Well by changing the conString a little I was able to connect without any problems either from the localnetwork or the internet.
if (TextUtils.isEmpty(port))
{
conString = "jdbc:jtds:sqlserver://" + host + ";databaseName=" + dbname + ";instance=" + instance;
}
else
{
conString = "jdbc:jtds:sqlserver://" + host + ":" + port + ";databaseName=" + dbname + ";instance=" + instance;
}
To
if (TextUtils.isEmpty(port))
{
conString = "jdbc:jtds:sqlserver://" + host + "/" + instance + ";DatabaseName=" +dbname;
}
else
{
conString = "jdbc:jtds:sqlserver://" + host + ":" + port + "/" + instance + ";DatabaseName=" + dbname;
}
Now works without any problems either using the public host or the localnetwork to access the db.
I am trying to use the different SIP port other than 5060.
I change the port of following code, but only the source port is changed.
The destination port of SIP server is still 5060.
// Create SIP transport. Error handling sample is shown
TransportConfig sipTpConfig = new TransportConfig();
sipTpConfig.setPort(Long.parseLong(port, 10));
/* Create transports. */
try {
ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, sipTpConfig);
}catch(Exception e){
System.out.println(e);
}
Does anyone have the idea how to do?
Thanks in advance!
You have to modify the account configuration:
final String acc_id = String.format(Locale.ENGLISH, "sip:%s#%s", username, domain);
final String registrar = String.format(Locale.ENGLISH, "sip:%s", domain);
final String proxy = String.format(Locale.ENGLISH, "sip:%s:%d;transport=%s;port=%d", domainip, port, protocol, port);
accCfg.setIdUri(acc_id);
accCfg.getRegConfig().setRegistrarUri(registrar);
AuthCredInfoVector creds = accCfg.getSipConfig().getAuthCreds();
creds.clear();
if (username.length() != 0) {
creds.add(new AuthCredInfo("Digest", "*", username, 0, password));
}
StringVector proxies = accCfg.getSipConfig().getProxies();
proxies.clear();
if (proxy.length() != 0) {
proxies.add(proxy);
}
accCfg.getNatConfig().setIceEnabled(true); // Enable ICE
lastRegStatus = null;
account.modify(accCfg);
i'm stuck at creating UDP connection between android phone(2.3) and my PC over wifi.
I know how to create a UDP connection in local server. My problem is do android support adhock network because whenever i try searching for my PC's wifi directly , it doesn't show it , hence i have to first create a virtual hotspot over my PC and then connect my phone to it .
After this , i simply try sending data packets from my phone to server running on my PC.
public class WifitestActivity extends Activity {
WifiManager w;
TextView status;
InetAddress server_ip;
int server_port = 9876;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
status = (TextView) findViewById(R.id.status);
w = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (!w.isWifiEnabled()) {
status.setText("switching ON wifi ");
w.setWifiEnabled(true);
} else {
status.setText("Its already ON ");
}
int x;
WifiInfo info = w.getConnectionInfo();
status.append("\n\nWiFi Status: " + info.toString());
x = info.getIpAddress();
String str = info.getMacAddress();
status.append("\n\nmac address===" + str + " ,ip===" + x);
try {
server_ip = InetAddress.getByName("192.168.181.1"); // ip of my server.How to dynamically update it
} catch (UnknownHostException e) {
status.append("Error at fetching inetAddress");
}
DatagramSocket s = new DatagramSocket(server_port, server_ip);
// **ERROR AT PREVIOUS LINE, I HAD TO FORCE STOP MY APP EVERTIME I RUN
// MY CODE**
String str = "TEST MESSAGE !!!";
byte b1[];
b1 = new byte[100];
b1 = str.getBytes();
DatagramPacket p1 = new DatagramPacket(b1, b1.length, server_ip,
server_port);
}
}
Server code running on my PC :
import java.io.*;
import java.net.*;
class server2
{
static InetAddress clientip;
static int clientport;
static DatagramPacket p3;
public static void main(String args[])throws Exception
{
DatagramSocket s = new DatagramSocket(9876);
byte b1[],b2[];
b1=new byte[100];
b2=new byte[100];
DatagramPacket p1 = new DatagramPacket(b1,b1.length);
s.receive(p1);
b1=p1.getData();
String str = new String( b1);
clientport = p1.getPort(); //packet mein save hota hai
clientip=p1.getAddress();
System.out.println("RECIEVED FROM CLIENT IP ="+clientip+" port="+clientport+" data="+str);
}
}
There is an error at client code (WifiTestActivity) and my app crashes whenever i try running it on my phone . Plzz help me out !
You need the Internet Permission. Add this to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
I am currently developing android XMPP client to communicate with the Tigase server setup locally.Before starting development on Android I am writing a simple java code on PC to test connectivity with XMPP server.My XMPP domain is my pc name "mwbn43-1" and administrator username and passwords are admin and tigase respectively.
Following is the snippet of the code I am using
class Test {
public static void main(String args[])throws Exception
{
System.setProperty("smack.debugEnabled", "true");
XMPPConnection.DEBUG_ENABLED = true;
ConnectionConfiguration config = new ConnectionConfiguration("mwbn43-1", 5222);
config.setCompressionEnabled(true);
config.setSASLAuthenticationEnabled(true);
XMPPConnection con = new XMPPConnection(config);
// Connect to the server
con.connect();
con.login("admin", "tigase");
Chat chat = con.getChatManager().createChat("aaphadke#mwbn43-1",
new MessageListener() {
public void processMessage(Chat chat, Message message) {
// Print out any messages we get back to standard out.
System.out.println("Received message: " + message);
}
});
try {
chat.sendMessage("Hi!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
String host = con.getHost();
String user = con.getUser();
String id = con.getConnectionID();
int port = con.getPort();
boolean i = false;
i = con.isConnected();
if (i)
System.out.println("Connected to host " + host + " via port " + port + " connection id is " + id);
System.out.println("User is " + user);
con.disconnect();
}
}
When I run this code I get following error
Exception in thread "main" Resource binding not offered by server:
at org.jivesoftware.smack.SASLAuthentication.bindResourceAndEstablishSession(SASLAuthenticatio n.java:416) at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:331)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:395)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at Test.main(Test.java:26)
I found this articles on the same problem but no concrete solution
here
Could anyone please tell me the solution for this problem.I checked the XMPPConnection.java file in the Smack API and it looks the same as given in the link solution.
Thanks,
Ameya
I found the solution to the problem as given in here
These are the lines I should add before I connect to the server
ConnectionConfiguration config = new ConnectionConfiguration("mwbn43-1", 5222);
config.setSASLAuthenticationEnabled(false);
XMPPConnection xmpp = new XMPPConnection(config);
Thanks for all your help
I think this is a problem with library, a bug. It does not handle protocol correctly. Before the user is authenticated there is no point of sending resource bind, hence it is not advertised by the server. The client should not complain about it.