繁体   English   中英

TCP连接无法正常工作

[英]tcp connect doesn't work java android

我是网络通讯和Java编程的新手。 我正在Android上制作应用程序(客户端),它将与计算机上的服务器连接。 这两个程序都连接到相同的Wifi网络。 但是我有一个问题。 当我从android客户端向服务器发送消息时,什么也没发生。 怎么了?

Android客户端

try
    {
        Socket s = new Socket("192.168.0.101", 5555);

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

        String outMsg = "";
        outMsg = "jakas wiadomosc";
        out.write(outMsg);
        out.flush();
        out.close();
        s.close();
    }

    catch(Exception e)
    {
        Log.d("Error", "something goes wrong");
    }
}

和计算机上的服务器

try
    {
        ServerSocket ss = null;

        ss = new ServerSocket(5555);

        Socket s = ss.accept();

        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        String incomingMsg = in.readLine() + System.getProperty("line.separator");
        jTextArea1.setText(incomingMsg);
        System.out.print(incomingMsg);

        in.close();

        s.close();
    }
    catch(Exception e)
    {
        System.out.print("not work");
    }

我用客户端程序做了一些事情:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class WifiActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wifi);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

public void buttonGo(View v){
     new PolaczenieWifi(this).execute();
  }



/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_pil_oot, container, false);
        return rootView;
    }
}
}

并使用AsyncTask创建另一个类PolaczenieWifi

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class PolaczenieWifi extends AsyncTask<Void, Void, Void> {

Activity wywolajActivity;

public PolaczenieWifi(Activity wywolajActivity) {
    this.wywolajActivity = wywolajActivity;
}

@Override
protected Void doInBackground(Void... arg0) {
try
{
    Socket s = new Socket("192.168.0.101", 5555);

    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

    String outMsg = "";
    outMsg = "jakas wiadomosc";
    out.write(outMsg);
    out.flush();
    out.close();
    s.close();
}

catch(Exception e)
{
    Log.d("Error", "something goes wrong");
    Log.d("bład", e.toString());
}
return null;
}

}

但是我不知道这个AsyncTask写得很好。 在按钮部分的activity_wifi中,我添加了android:onClick="buttonGo"

服务器代码不变(在Netbeans中制成):

public static void main(String args[]) throws IOException {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(WifiFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(WifiFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(WifiFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(WifiFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new WifiFrame().setVisible(true);
        }
    });

    try
    {
        ServerSocket ss = null;

        ss = new ServerSocket(5555);

        Socket s = ss.accept();

        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        String incomingMsg = in.readLine() + System.getProperty("line.separator");
        jTextArea1.setText(incomingMsg);
        System.out.print(incomingMsg);

        in.close();

        s.close();
    }
    catch(IOException e)
    {
        System.out.print("Whoops! It didn't work!\n");
        System.out.print(e.toString());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM