Wednesday, February 12, 2014

Ask God to help look great, socket Why can not achieve data transfer.


            
Server-side code:
import java.net *;.
import java.io. *;
/ / Server
public class NfcServer {
public static void main (String [] args) throws IOException {
/ / Create a ServerSocket, Socket to listen for client connection requests
ServerSocket ss = new ServerSocket (30000);
/ / Use cycle continuously receives from a client a request
while (true) {
Socket s = ss.accept ();
BufferedReader br = new BufferedReader (new InputStreamReader (s.getInputStream ()));
String line = br.readLine ();
System.out.println (line);

br.close ();
s.close ();
}
}
}
This is the client a (mainly used for testing):
public class MainActivity extends Activity {
EditText show;
@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
show = (EditText) findViewById (R.id.show);
final String zifu = "hyuuijhjkj";
/ / Legend of the anonymous inner class!
new Thread () {
public void run () {
try {
Socket socket = new Socket ("192.168.1.153", 30000);
OutputStream os = socket.getOutputStream ();
os.write (zifu.getBytes ());

os.close ();
socket.close ();
} Catch (IOException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}

}
}. Start ()
}
}

Reply:
This is the client two:
Note: This code is nfc read and write operations. The amount of code looks great, but the fact of God do not control others, help me find onNewIntent this method first if it.
I used the client and server to do a test, you can communicate, the server can also print out a string obtained from the client. But when I put the client a code ported to onNewIntent in time, do not work anymore, why is this? My body is not also pass the String type it? Where is the problem? Before I received the service side of the line judge, empty prints XXX, non-empty prints XX, the results on the server side without any reaction
public class MainActivity extends Activity {
private static final String TAG = "stickynotes";
/ / Private boolean mResumed = false;
private boolean mWriteMode = false;
NfcAdapter mNfcAdapter;
EditText mNote;
EditText mNoteRead;
PendingIntent mNfcPendingIntent;
IntentFilter [] mWriteTagFilters;
IntentFilter [] mNdefExchangeFilters;

/ ** Called when the activity is first created. * /
@ Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.main);

/ / To write label text edit box
mNote = ((EditText) findViewById (R.id.note));
mNote.addTextChangedListener (mTextWatcher);
/ / Display the text read labels
mNoteRead = ((EditText) findViewById (R.id.noteRead));
/ / Get a default NFC Adapter
mNfcAdapter = NfcAdapter.getDefaultAdapter (this);

if (mNfcAdapter == null) {
toast ("device does not support nfc!");
return;
}
/ / Set button to listen
. findViewById (R.id.write_tag) setOnClickListener (mTagWriter);
. findViewById (R.id.read_tag) setOnClickListener (mTagRead);

/ / Handle all of our received NFC intents in this activity.
/ / Create a PendingIntent object, android system can scan the contents of the label when the label is filled to this object.
/ / Start the first step in the foreground scheduling system. (Foreground activity scheduling system allows the interception and declare themselves priority Intent Intent)
mNfcPendingIntent = PendingIntent.getActivity (this, 0, new Intent (this,
getClass ()) addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);.

/ / Intent filters for reading a note from a tag or exchanging over p2p.
/ / Matches NfcAdapter.ACTION_NDEF_DISCOVERED the action of IntentFilter, this action without data
IntentFilter ndefDetected = new IntentFilter (
NfcAdapter.ACTION_NDEF_DISCOVERED);

try {
/ / AddDataType: give this IntentFilter Intent to add a new data type matching
ndefDetected.addDataType ("text / plain");
} Catch (MalformedMimeTypeException e) {
}
mNdefExchangeFilters = new IntentFilter [] {ndefDetected};

/ / Intent filters for writing to a tag
IntentFilter tagDetected = new IntentFilter (
NfcAdapter.ACTION_TAG_DISCOVERED);
mWriteTagFilters = new IntentFilter [] {tagDetected};


}

@ Override
protected void onResume () {
super.onResume ();
/ / MResumed = true;
/ / Sticky notes received from Android
/ / GetIntent (): Returns the intent to start this Activity here is the key code to get NDEF Message.!
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals (getIntent (). getAction ())) {
NdefMessage [] messages = getNdefMessages (getIntent ());
byte [] payload = messages [0] getRecords () [0] getPayload ();..
/ / Since writing method: read text from a label added to the view in
setNoteBody (new String (payload));
/ / SetIntent (intent newIntent): change the intent
returned by the getIntentsetIntent (new Intent ());. / / Consume this intent
}
if (mNfcAdapter! = null) {
enableNdefExchangeMode ();
}
}

@ Override
protected void onPause () {
super.onPause ();
/ / MResumed = false;
if (mNfcAdapter! = null) {
mNfcAdapter.disableForegroundNdefPush (this);
}
}
/ / When you first open the app seems to be used to display the label
newIntent@ Override
protected void onNewIntent (Intent intent) {
/ / NDEF exchange mode
if (! mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ())) {
NdefMessage [] msgs = getNdefMessages (intent);
final String body = new String (msgs [0] getRecords () [0] getPayload ()..);
/ / Send a message to the server
new Thread () {
public void run () {
try {
Socket socket = new Socket ("192.168.1.153", 30000);
OutputStream os = socket.getOutputStream ();
os.write (body.getBytes ());

os.close ();
socket.close ();
} Catch (IOException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}

}
}. Start ()
/ / Display message to the edit box read, this is a custom method
setNoteBody (body);
}
/ / Tag writing mode
if (mWriteMode
&& NfcAdapter.ACTION_TAG_DISCOVERED.equals (intent.getAction ())) {
Tag detectedTag = intent.getParcelableExtra (NfcAdapter.EXTRA_TAG);
writeTag (getNoteAsNdef (), detectedTag);
}
}

private TextWatcher mTextWatcher = new TextWatcher () {

@ Override
public void onTextChanged (CharSequence arg0, int arg1, int arg2,
int arg3) {

}

@ Override
public void beforeTextChanged (CharSequence arg0, int arg1, int arg2,
int arg3) {

}

@ Override
public void afterTextChanged (Editable arg0) {
/ / If (mResumed) {
/ / MNfcAdapter.enableForegroundNdefPush (MainActivity.this,
/ / GetNoteAsNdef ());
/ /}
}
};
/ / Listener into the edit box
private View.OnClickListener mTagWriter = new View.OnClickListener () {
@ Override
public void onClick (View arg0) {
/ / Write to a tag for as long as the dialog is shown.
disableNdefExchangeMode ();
enableTagWriteMode ();

new AlertDialog.Builder (MainActivity.this)
. SetTitle ("Touch tag to write")
. SetOnCancelListener (
new DialogInterface.OnCancelListener () {
@ Override
public void onCancel (DialogInterface dialog) {
disableTagWriteMode ();
enableNdefExchangeMode ();
}
..}) Create () show ();
}
};

private View.OnClickListener mTagRead = new View.OnClickListener () {
@ Override
public void onClick (View arg0) {
/ / Write to a tag for as long as the dialog is shown.
disableTagWriteMode ();
enableNdefExchangeMode ();

new AlertDialog.Builder (MainActivity.this)
. SetTitle ("Touch tag to read")
. SetOnCancelListener (
new DialogInterface.OnCancelListener () {
@ Override
public void onCancel (DialogInterface dialog) {
disableTagWriteMode ();
enableNdefExchangeMode ();
}
..}) Create () show ();
}
};

/ / Add read tagged text (body) to view the
private void setNoteBody (String body) {
Editable text = mNoteRead.getText ();
text.clear ();
text.append (body);
}
/ / Encryption
private NdefMessage getNoteAsNdef () {
try {
DESPlus des = new DESPlus ("123456") ;/ / custom key
String encrypted = des.encrypt (mNote.getText () toString ().);
byte [] textBytes = encrypted.getBytes ();
NdefRecord textRecord = new NdefRecord (NdefRecord.TNF_MIME_MEDIA,
. "Text / plain" getBytes (), new byte [] {}, textBytes);
return new NdefMessage (new NdefRecord [] {textRecord});
} Catch (Exception e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
return null;
}
}

/ / Get the NDEF Message
NdefMessage [] getNdefMessages (Intent intent) {
/ / Parse the intent
NdefMessage [] msgs = null;
String action = intent.getAction ();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals (action)
| | NfcAdapter.ACTION_NDEF_DISCOVERED.equals (action)) {
Parcelable [] rawMsgs = intent
. GetParcelableArrayExtra (NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs! = null) {
msgs = new NdefMessage [rawMsgs.length];
for (int i = 0; i msgs [i] = (NdefMessage) rawMsgs [i];
}
} Else {
/ / Unknown tag type
byte [] empty = new byte [] {};
NdefRecord record = new NdefRecord (NdefRecord.TNF_UNKNOWN,
empty, empty, empty);
NdefMessage msg = new NdefMessage (new NdefRecord [] {record});
msgs = new NdefMessage [] {msg};
}
} Else {
Log.d (TAG, "Unknown intent.");
finish ();
}
return msgs;
}

private void enableNdefExchangeMode () {
/ / MNfcAdapter.enableForegroundNdefPush (MainActivity.this,
/ / GetNoteAsNdef ());
mNfcAdapter.enableForegroundDispatch (this, mNfcPendingIntent,
mNdefExchangeFilters, null);
}

private void disableNdefExchangeMode () {
mNfcAdapter.disableForegroundNdefPush (this);
mNfcAdapter.disableForegroundDispatch (this);
}

private void enableTagWriteMode () {
mWriteMode = true;
IntentFilter tagDetected = new IntentFilter (
NfcAdapter.ACTION_TAG_DISCOVERED);
mWriteTagFilters = new IntentFilter [] {tagDetected};
mNfcAdapter.enableForegroundDispatch (this, mNfcPendingIntent,
mWriteTagFilters, null);
}

private void disableTagWriteMode () {
mWriteMode = false;
mNfcAdapter.disableForegroundDispatch (this);
}

boolean writeTag (NdefMessage message, Tag tag) {
. int size = message.toByteArray () length;

try {
Ndef ndef = Ndef.get (tag);
if (ndef! = null) {
ndef.connect ();

if (! ndef.isWritable ()) {
toast ("Tag is read-only.");
return false;
}
if (ndef.getMaxSize () toast ("Tag capacity is" + ndef.getMaxSize ()
+ "Bytes, message is" + size + "bytes.");
return false;
}

ndef.writeNdefMessage (message);
toast ("write data successfully");
return true;
} Else {
NdefFormatable format = NdefFormatable.get (tag);
if (format! = null) {
try {
format.connect ();
format.format (message);
toast ("Formatted tag and wrote message");
return true;
} Catch (IOException e) {
toast ("Failed to format tag.");
return false;
}
} Else {
toast ("Tag doesn't support NDEF.");
return false;
}
}
} Catch (Exception e) {
toast ("failed to write data");
}

return false;
}

private void toast (String text) {
Toast.makeText (this, text, Toast.LENGTH_SHORT) show ();.
}

}
Reply:
Is this the problem of cattle B? Asked so many places nobody answer ah
Reply:
Perhaps a detail of place, did not notice
Reply:
There may be a coding problem? You are not sent by the client 2 body, sending letters to try?
Reply:
references, 4th Floor zzj000 reply:
there may be coding problems? You are not sent by the client 2 body, sending letters to try?

I tried what you said, the server still did not respond. I suspect that is not connected not connected. However, a client can ah. I now suspect that it was onNewIntent this method, I just did not take long to learn Andrews, Andrews understanding of the operating mechanism is not very thorough
Reply:
1 Your server is read by line, so you also need to send a client behind a string line mode in accordance with the need for line breaks.
Reply:
There is no first-check socket connection is successful
Reply:
final String body = new String (msgs [0] getRecords () [0] getPayload ()..);
?
final String body = msgs [0] getRecords () [0] getPayload ();..

Reply:
if (! mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ())) {
Come in yet?
Reply:
1 client is the real machine or a simulator?
2.IP problem. The client can not directly use the IP;
3 If the fax machine, to ensure open wifi, wifi network and ensure that energy and server to ping.
Reply:
reference to the 7th floor pengguohua1988 reply:
first detected about socket has no connection success

White inquired how to detect. . . .
Reply:
reference to the 9th floor pengguohua1988 reply:
if {
(mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ())!)Come in yet?

Should come in, because new Thread behind this phrase setBodyNote internal class method execution, and I edit box on the phone to get the desired string is encrypted using des algorithm is of type String
Reply:
reference to the 10th floor an_zhiruo reply:.
1 client is the real machine or a simulator?
2.IP problem. The client can not directly use the IP;
3 If the fax machine, to ensure open wifi, wifi network and ensure that energy and server to ping.

Great God Hello
1, the client is my millet phone, the server is a PC
2, can I use a code to the client on the phone is running with the IP, to achieve a data transfer ah
3, ah, mobile phone and PC in, tried on the same network segment between the mobile phone is loaded on the PC in written jsp page.
Reply:
reference to the 12th floor fyxamlj reply:
Quote: references to the 9th floor pengguohua1988 reply:

if (! mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ())) {
Come in yet?

Should come in, because new Thread behind this phrase setBodyNote internal class method execution, and I edit box on the phone to get the desired string is encrypted using des algorithm is of type String


You add a print server. There are about a client when the print link. Estimate your socket did not link.
Reply:
reference to the 14th floor an_zhiruo reply:
Quote: references to the 12th floor fyxamlj reply:

Quote: references to the 9th floor pengguohua1988 reply:

if (! mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ())) {
Come in yet?

Should come in, because new Thread behind this phrase setBodyNote internal class method execution, and I edit box on the phone to get the desired string is encrypted using des algorithm is of type String


You add a print server. There are about a client when the print link. Estimate your socket did not link.

I was in the service side of the Socket s = ss.sccept (); sentence underneath the System.out.println ("connection status is:" + s.isConnected ()); sentence. With a test client, you can output true. But with two test client, server, or no response, the output is not output true nor false. . . . .
Reply:
reference to the 7th floor pengguohua1988 reply:
first detected about socket has no connection success

I was in the service side of the Socket s = ss.sccept (); sentence underneath the System.out.println ("connection status is:" + s.isConnected ()); sentence. With a test client, you can output true. But with two test client, server, or no response, the output is not output true nor false. . . . .
        

Reply:
reference to the 6th floor birdsaction reply:.
1 Your server is read by line, so you also need to send a client in accordance with the character line mode behind the string needs to have a line break.

Looks like it should not be a string of problems, the server is no response, see my other reply. I also tried in the body plus "\ n", wood useful service side or no response.
Reply:
Server socket is not bound port?
Reply:
Ask for help answer ah ah ah ah ah
Reply:
reference to the 16th floor fyxamlj reply:
Quote: references to the 7th floor pengguohua1988 reply:

There is no first-check socket connection is successful

I was in the service side of the Socket s = ss.sccept (); sentence underneath the System.out.println ("connection status is:" + s.isConnected ()); sentence. With a test client, you can output true. But with two test client, server, or no response, the output is not output true nor false. . . . .

That does not prove that you did not perform to the second link socket it
Reply:
reference to the 12th floor fyxamlj reply:
Quote: references to the 9th floor pengguohua1988 reply:

if (! mWriteMode && NfcAdapter.ACTION_NDEF_DISCOVERED.equals (intent.getAction ())) {
Come in yet?

Should come in, because new Thread behind this phrase setBodyNote internal class method execution, and I edit box on the phone to get the desired string is encrypted using des algorithm is of type String


You would keep the implementation of the code within a thread, the look is not throwing an exception of it!
Reply:
cited 20 floor pengguohua1988 reply:
Quote: references to the 16th floor fyxamlj reply:

Quote: references to the 7th floor pengguohua1988 reply:

There is no first-check socket connection is successful

I was in the service side of the Socket s = ss.sccept (); sentence underneath the System.out.println ("connection status is:" + s.isConnected ()); sentence. With a test client, you can output true. But with two test client, server, or no response, the output is not output true nor false. . . . .

That does not prove that you did not perform to the second link socket it

But why, I really wonder. I put this anonymous inner class dismissed, I rewrote a Thread class, and then pass the reference in the past. In fact, not much difference, is no longer as executed only once as anonymous inner classes. It is still a client can, the client two no response. I catch my feet soon gave up. Really do not understand
Reply:
cited 22 floor fyxamlj reply:
Quote: 20th Floor pengguohua1988 cited reply:

Quote: 16th Floor reply fyxamlj of references:

Quote: references to the 7th floor pengguohua1988 reply:

There is no first-check socket connection is successful

I was in the service side of the Socket s = ss.sccept (); sentence underneath the System.out.println ("connection status is:" + s.isConnected ()); sentence. With a test client, you can output true. But with two test client, server, or no response, the output is not output true nor false. . . . .

That does not prove that you did not perform to the second link socket it

But why, I really wonder. I put this anonymous inner class dismissed, I rewrote a Thread class, and then pass the reference in the past. In fact, not much difference, is no longer as executed only once as anonymous inner classes. It is still a client can, the client two no response. I catch my feet soon gave up. Really do not understand

You put the client two threads try to remove
Reply:
In addition, you quickly learn it DEBUG
Reply:
cited 23 floor pengguohua1988 reply:
Quote: references 22 F fyxamlj reply:

Quote: 20th Floor pengguohua1988 cited reply:

Quote: 16th Floor reply fyxamlj of references:

Quote: references to the 7th floor pengguohua1988 reply:

There is no first-check socket connection is successful

I was in the service side of the Socket s = ss.sccept (); sentence underneath the System.out.println ("connection status is:" + s.isConnected ()); sentence. With a test client, you can output true. But with two test client, server, or no response, the output is not output true nor false. . . . .

That does not prove that you did not perform to the second link socket it

But why, I really wonder. I put this anonymous inner class dismissed, I rewrote a Thread class, and then pass the reference in the past. In fact, not much difference, is no longer as executed only once as anonymous inner classes. It is still a client can, the client two no response. I catch my feet soon gave up. Really do not understand

You put the client two threads try to remove

Tried error. android does not allow the UI thread using socket, so just open a new thread.
debug how to learn, seeking further detail, refer to Ming Road bar. I only know that struts in the debug. android how to use
Reply:
100 does not have to recruit people who can solve the problem! I suspect the problem is part of the code of the nfc.
Reply:
Seeking solutions! ! ! !
Reply:
The landlord to see if the configuration file is not authorized to access the Internet problem!
Reply:
My goodness! ! ! ! ! You're not the first one connected to it? The answer can be right?

No comments:

Post a Comment