Monday, April 7, 2014

Socket Communications, written in java server and client have no problem. But the android as a client following error


Code is as follows:
package com.cxw.seventask;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SevenTaskMainActivity extends Activity implements Runnable {
private EditText username, serverIP, historyEdit, messageEdit;
private Button loginButton, cancelButton, sendButton;
private String username1, ip, chat_txt, chat_in;
public static final int PORT = 8521;
Socket socket;
Thread thread;
DataInputStream in;
DataOutputStream out;
boolean flag = false;
@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.main);
username = (EditText) findViewById (R.id.editText1);
serverIP = (EditText) findViewById (R.id.editText2);
historyEdit = (EditText) findViewById (R.id.editText3);
messageEdit = (EditText) findViewById (R.id.editText4);
loginButton = (Button) findViewById (R.id.button1);
cancelButton = (Button) findViewById (R.id.button2);
sendButton = (Button) findViewById (R.id.button3);
loginButton.setOnClickListener (listener);
cancelButton.setOnClickListener (listener);
sendButton.setOnClickListener (listener);

}
View.OnClickListener listener = new View.OnClickListener () {

@ Override
public void onClick (View view) {
/ / TODO Auto-generated method stub
switch (view.getId ())
{
case R.id.button1:
if (flag == true)
{
Toast.makeText (SevenTaskMainActivity.this, "has logged over!", Toast.LENGTH_SHORT) show ();.
return;
}
username1 = username.getText () toString ();.
ip = serverIP.getText () toString ();.
if (username1! = "" && username! = null && username1! = "User Input" && ip! = null)
{
try {

socket = new Socket (ip, PORT);
/ / Create the client data input and output streams, for sending or receiving data to the server
in = new DataInputStream (socket.getInputStream ());
out = new DataOutputStream (socket.getOutputStream ());
Date now = new Date (System.currentTimeMillis ());
SimpleDateFormat format = new SimpleDateFormat ("hh: mm: ss");
String nowStr = format.format (now);
out.writeUTF ("$ $" + username1 + "" + nowStr + "on the line");
} Catch (IOException e1)
{
System.out.println ("Unable to connect");
}
thread = new Thread (SevenTaskMainActivity.this);
thread.start ();
flag = true;
}
break;
case R.id.button3:
if (flag == false)
{
Toast.makeText (SevenTaskMainActivity.this, "have not logged in!", Toast.LENGTH_SHORT) show ();.
return;
}
chat_txt = messageEdit.toString () toString ();.
if (chat_txt! = null)
{
Date now = new Date (System.currentTimeMillis ());
SimpleDateFormat format = new SimpleDateFormat ("hh: mm: ss");
String nowstr = format.format (now);
try
{
out.writeUTF ("^ _ ^" + username1 + "" + nowstr + "says \ n" + chat_txt);
} Catch (IOException e2)
{

}
}
else
{
try
{
out.writeUTF ("Speak");
} Catch (IOException e3)
{

}
}
break;
case R.id.button2:
if (flag == true)
{
if (flag == false)
{
Toast.makeText (SevenTaskMainActivity.this, "not logged in before, please log in!", Toast.LENGTH_SHORT) show ();.
return;
}
try
{
out.writeUTF ("==" + username1 + "is down");
out.close ();
in.close ();
socket.close ();
} Catch (IOException e4)
{

}
}
flag = false;
Toast.makeText (SevenTaskMainActivity.this, "has exited", Toast.LENGTH_SHORT) show ();.
break;
}

}
};
@ Override
public boolean onCreateOptionsMenu (Menu menu) {
/ / Inflate the menu; this adds items to the action bar if it is present
.getMenuInflater () inflate (R.menu.activity_seven_task_main, menu);.
return true;
}
@ Override
public void run () {
/ / TODO Auto-generated method stub
while (true)
{
try
{
chat_in = in.readUTF ();
chat_in = chat_in + "\ n";
mHandler.sendMessage (mHandler.obtainMessage ());
} Catch (IOException e)
{}
}

}
Handler mHandler = new Handler ()
{
public void handleMessage (Message msg)
{
historyEdit.append (chat_in);
super.handleMessage (msg);
}
};

}

Error follows:
0-01 06:58:25.195: D / AndroidRuntime (22152): Shutting down VM
10-01 06:58:25.195: W / dalvikvm (22152): threadid = 1: thread exiting with uncaught exception (group = 0x40a70930)
10-01 06:58:25.272: E / AndroidRuntime (22152): FATAL EXCEPTION: main
10-01 06:58:25.272: E / AndroidRuntime (22152): android.os.NetworkOnMainThreadException
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork (StrictMode.java: 1117)
10-01 06:58:25.272: E / AndroidRuntime (22152): at libcore.io.BlockGuardOs.connect (BlockGuardOs.java: 84)
10-01 06:58:25.272: E / AndroidRuntime (22152): at libcore.io.IoBridge.connectErrno (IoBridge.java: 127)
10-01 06:58:25.272: E / AndroidRuntime (22152): at libcore.io.IoBridge.connect (IoBridge.java: 112)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.net.PlainSocketImpl.connect (PlainSocketImpl.java: 192)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.net.PlainSocketImpl.connect (PlainSocketImpl.java: 172)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.net.Socket.startupSocket (Socket.java: 566)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.net.Socket.tryAllAddresses (Socket.java: 127)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.net.Socket . (Socket.java: 177)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.net.Socket . (Socket.java: 149)
10-01 06:58:25.272: E / AndroidRuntime (22152): at com.cxw.seventask.SevenTaskMainActivity $ 1.onClick (SevenTaskMainActivity.java: 65)
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.view.View.performClick (View.java: 4202)
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.view.View $ PerformClick.run (View.java: 17340)
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.os.Handler.handleCallback (Handler.java: 725)
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.os.Handler.dispatchMessage (Handler.java: 92)
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.os.Looper.loop (Looper.java: 137)
10-01 06:58:25.272: E / AndroidRuntime (22152): at android.app.ActivityThread.main (ActivityThread.java: 5039)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.lang.reflect.Method.invokeNative (Native Method)
10-01 06:58:25.272: E / AndroidRuntime (22152): at java.lang.reflect.Method.invoke (Method.java: 511)
10-01 06:58:25.272: E / AndroidRuntime (22152): at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java: 793)
10-01 06:58:25.272: E / AndroidRuntime (22152): at com.android.internal.os.ZygoteInit.main (ZygoteInit.java: 560)
10-01 06:58:25.272: E / AndroidRuntime (22152): at dalvik.system.NativeStart.main (Native Method)
10-01 06:58:39.496: I / Process (22152): Sending signal PID:. 22152 SIG: 9
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
NetworkOnMainThreadException
In the main UI thread to do network operations, before the operation returns, UI will not respond to user actions, or 5 seconds after the cause has not yet returned ANR, affecting the user experience.
4.0 has been allowed to do so in the future, you need to put in a new network operating thread.
Reply:
Now Andrews network communication must be carried out in the thread, remember that there is no such requirement.
Reply:
cited a floor tantahe reply:
NetworkOnMainThreadException
In the main UI thread to do network operations, before the operation returns, UI will not respond to user actions, or 5 seconds after the cause has not yet returned ANR, affecting the user experience.
4.0 has been allowed to do so in the future, you need to put in a new network operating thread.

How to change? Great God. Or give me some version 4.0 or socket programming
Reply:
reference to the second floor tcmakebest reply:
Andrews network communication must now be carried out in the thread, remember that there is no such requirement.

I say this program right, as long as the modified version of the line of what you
Reply:
Your program may be able to run at low ANDROID version, but it does not mean that this is right. Even if you can run, is limited to the class for the test ah, truly complete program, and not to the time-consuming thread from the UI thread.
Reply:
references, 5th Floor sjyhehe reply:
your program may be able to run at low ANDROID version, but it does not mean that this is right. Even if you can run, is limited to the class for the test ah, truly complete program, and not to the time-consuming thread from the UI thread.

Just beginning to learn android, the books are not on this knowledge, I do not know why you know it? Can you give some of your learning android Socket canon
Reply:
 package com.cxw.seventask; 

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SevenTaskMainActivity extends Activity implements Runnable {
private EditText username, serverIP, historyEdit, messageEdit;
private Button loginButton, cancelButton, sendButton;
private String username1, ip, chat_txt, chat_in;
public static final int PORT = 8521;
Socket socket;
Thread thread;
DataInputStream in;
DataOutputStream out;
boolean flag = false;

@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.main);
username = (EditText) findViewById (R.id.editText1);
serverIP = (EditText) findViewById (R.id.editText2);
historyEdit = (EditText) findViewById (R.id.editText3);
messageEdit = (EditText) findViewById (R.id.editText4);
loginButton = (Button) findViewById (R.id.button1);
cancelButton = (Button) findViewById (R.id.button2);
sendButton = (Button) findViewById (R.id.button3);
loginButton.setOnClickListener (listener);
cancelButton.setOnClickListener (listener);
sendButton.setOnClickListener (listener);

}

View.OnClickListener listener = new View.OnClickListener () {

@ Override
public void onClick (View view) {
/ / TODO Auto-generated method stub
switch (view.getId ()) {
case R.id.button1:
if (flag == true) {
Toast.makeText (SevenTaskMainActivity.this, "has logged over!",
. Toast.LENGTH_SHORT) show ();
return;
}
username1 = username.getText () toString ();.
ip = serverIP.getText () toString ();.
if (username1! = "" && username! = null && username1! = "user input"
&& Ip! = Null) {
(New Thread () {/ / Here's a new thread, network operations into here thread

@ Override
public void run () {
super.run ();
try {

socket = new Socket (ip, PORT);
/ / Create the client data input and output streams, for sending or receiving data to the server
in = new DataInputStream (socket.getInputStream ());
out = new DataOutputStream (socket.getOutputStream ());
Date now = new Date (System.currentTimeMillis ());
SimpleDateFormat format = new SimpleDateFormat (
"Hh: mm: ss");
String nowStr = format.format (now);
out.writeUTF ("$ $" + username1 + "" + nowStr + "on the line");
} Catch (IOException e1) {
System.out.println ("Unable to connect");
}
}

.}) Start ();

thread = new Thread (SevenTaskMainActivity.this);
thread.start ();
flag = true;
}
break;
case R.id.button3:
if (flag == false) {
Toast.makeText (SevenTaskMainActivity.this, "have not logged in!",
. Toast.LENGTH_SHORT) show ();
return;
}
chat_txt = messageEdit.toString () toString ();.
if (chat_txt! = null) {
Date now = new Date (System.currentTimeMillis ());
SimpleDateFormat format = new SimpleDateFormat ("hh: mm: ss");
String nowstr = format.format (now);
try {
out.writeUTF ("^ _ ^" + username1 + "" + nowstr + "says \ n"
+ Chat_txt);
} Catch (IOException e2) {

}
} Else {
try {
out.writeUTF ("Speak");
} Catch (IOException e3) {

}
}
break;
case R.id.button2:
if (flag == true) {
if (flag == false) {
Toast.makeText (SevenTaskMainActivity.this,
"There is no logged in, please login!", Toast.LENGTH_SHORT) show ();.
return;
}
(New Thread () {/ / Here's a new thread, network operations into here thread

@ Override
public void run () {
super.run ();
try {
out.writeUTF ("==" + username1 + "is down");
out.close ();
in.close ();
socket.close ();
} Catch (IOException e4) {

}
}

.}) Start ();

}
flag = false;
Toast.makeText (SevenTaskMainActivity.this, "has exited",
. Toast.LENGTH_SHORT) show ();
break;
}

}
};

@ Override
public boolean onCreateOptionsMenu (Menu menu) {
/ / Inflate the menu; this adds items to the action bar if it is present
.getMenuInflater () inflate (R.menu.activity_seven_task_main, menu);.
return true;
}

@ Override
public void run () {
/ / TODO Auto-generated method stub
while (true) {
try {
chat_in = in.readUTF ();
chat_in = chat_in + "\ n";
mHandler.sendMessage (mHandler.obtainMessage ());
} Catch (IOException e) {
}
}

}

Handler mHandler = new Handler () {
public void handleMessage (Message msg) {
historyEdit.append (chat_in);
super.handleMessage (msg);
}
};

}


Look at those two places comment, the network operating on a new thread. This does not appear NetworkOnMainThreadException.
Reply:
Network operation can not be placed in the main thread

No comments:

Post a Comment