58,454
社区成员
发帖
与我相关
我的任务
分享
//现在直接在这里设定一个socket只为了连接用,
public class ConnectJudgment {
public PrintWriter out;
public String foreMessage="connect before";
public String laterMessage="connect before";
public static String Ip="";
public static int port=50001;
public static int flag = 0;
public static Socket socket = null;
protected ConnectJudgment() {
connectTask task = new connectTask(this);
task.execute();
}
class connectTask extends AsyncTask<String,Integer, String>
{
public connectTask(ConnectJudgment connectJudgment) {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... params) {
try{
//connect to server with ip&port
socket = new Socket(InetAddress.getByName(Ip),port);
flag = 1;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ConnectJudgment.socket.getOutputStream())), true);
while(socket.isConnected())
{
if(!foreMessage.equals(laterMessage))
{
out.println(laterMessage);
out.flush();
foreMessage = laterMessage;
}
}
//socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
}
public class Connection_Activity extends ActionBarActivity{
//this is for hide soft keyboard.
private View connectionLayout;
//sp is to save data from last time.
private SharedPreferences sp;
//show information when you r logging.
private ProgressDialog progressDialog;
private EditText Ip;
private String lastIp = "";
private Button connectionButton;
protected PrintWriter out;
private ConnectJudgment con;
//if ip is the right rule.
public boolean isIPAddress(String str)
{
Pattern pattern = Pattern.compile( "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b" );
return pattern.matcher( str ).matches();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_connection);
//initpush();
//hide soft keyboard from current view.
connectionLayout = (View)findViewById(R.id.connectionlayout);
connectionLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
});
//initial sp object .default mode is 0.
sp=this.getSharedPreferences("ip",0);
//get the control
Ip = (EditText)findViewById(R.id.IpAddress);
//to read if there is any data from last time inputing.
readSharedPreferences();
connectionButton = (Button)findViewById(R.id.connectButton);
connectionButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
//这里得到了ip地址,是另外的函数不管这个
if(isIPAddress(ConnectJudgment.Ip))
{
saveSharedPreferences();
con = new ConnectJudgment();
try
{
//show waiting info
progressDialog = ProgressDialog.show(Connection_Activity.this, "",
getResources().getString(R.string.waitConnection));
progressDialog.setCancelable(false);
new Handler().postDelayed(run,5000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), R.string.IpWrong, Toast.LENGTH_LONG).show();
}
}
});
}
//wait a few seconds to jump to another activity.
Runnable run = new Runnable()
{
public void run()
{
if(ConnectJudgment.flag == 1)
{
//理论上来讲,后台的循环程序一直不断地检测两次message有没有变化
//而message一旦变了,就进入out.println()发送数据。
con.laterMessage = "";
//click the connect button
Intent intent = new Intent();
intent.setClass(Connection_Activity.this, SocketTest.class);
startActivity(intent);
progressDialog.cancel();
finish();
}
else
{
progressDialog.cancel();
Toast.makeText(getApplicationContext(), R.string.socketWrong, Toast.LENGTH_LONG).show();
}
}
};
//save data to use it next time.
private void saveSharedPreferences(){
SharedPreferences.Editor editor=sp.edit();
editor.putString("Ip", Ip.getText().toString());
editor.commit();
}
//get data from last inputing.
private void readSharedPreferences() {
String IpAddress=sp.getString("Ip", "");
Ip.setText(IpAddress);
}
}
public class SocketTest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.socket_test);
String message = "sent failed";
sendMessage(message);
}
public void sendMessage(String mess)
{
try {
PrintWriter out = null;
if(ConnectJudgment.socket.isConnected())
{
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ConnectJudgment.socket.getOutputStream())), true);
out.println(mess);
}
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run() {
// TODO Auto-generated method stub
try
{
//get a port from system which is free now.
serverSocket= new ServerSocket(0);
Port = serverSocket.getLocalPort();
while(true)
{
//accept the data from client
Socket client = serverSocket.accept();
System.out.println("accept");
try
{
//get the data info
//inputstream to receive data,outputstream to write data
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
//convert the info into string
info = in.readLine();
System.out.println("info: "+info);
runCommand(info);
//turn off the source
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
client.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}