当前位置: 代码迷 >> Android >> Android客户端Socket联接PC服务器端(转载加评论)
  详细解决方案

Android客户端Socket联接PC服务器端(转载加评论)

热度:61   发布时间:2016-05-01 17:13:12.0
Android客户端Socket连接PC服务器端(转载加评论)
先上代码:
1. SocketConnect.java文件
Java代码 
package cn.com;  
 
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
import java.io.PrintWriter;  
import java.net.Socket;  
 
import android.app.Activity;  
import android.os.Bundle;  
import android.util.Log;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.TextView;  
 
public class SocketConnect extends Activity {  
 
    private TextView mTextView = null;  
    private EditText mEditText = null;  
    private Button mButton = null;  
 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
 
        mButton = (Button) findViewById(R.id.Button01);  
        mTextView = (TextView) findViewById(R.id.TextView01);  
        mEditText = (EditText) findViewById(R.id.EditText01);  
 
        // 登陆  
        mButton.setOnClickListener(new OnClickListener() {  
            public void onClick(View v) {  
                Socket socket = null;  
                String message = mEditText.getText().toString() + "\r\n";  
                try {  
                    // 创建Socket  
                    socket = new Socket("192.168.1.100", 5554); // 查看本机IP,每次开机都不同  
                    // 向服务器发送消息  
                    PrintWriter out = new PrintWriter(new BufferedWriter(  
                            new OutputStreamWriter(socket.getOutputStream())),  
                            true);  
                    out.println(message);  
 
                    // 接收来自服务器的消息  
                    BufferedReader br = new BufferedReader(  
                            new InputStreamReader(socket.getInputStream()));  
                    String msg = br.readLine();  
 
                    if (msg != null) {  
                        mTextView.setText(msg);  
                    } else {  
                        mTextView.setText("数据错误!");  
                    }  
                    // 关闭流  
                    out.close();  
                    br.close();  
                    // 关闭Socket  
                    socket.close();  
                } catch (Exception e) {  
                    // TODO: handle exception  
                    Log.e("", e.toString());  
                }  
            }  
        });  
    }  


package cn.com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SocketConnect extends Activity {

private TextView mTextView = null;
private EditText mEditText = null;
private Button mButton = null;

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

mButton = (Button) findViewById(R.id.Button01);
mTextView = (TextView) findViewById(R.id.TextView01);
mEditText = (EditText) findViewById(R.id.EditText01);

// 登陆
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Socket socket = null;
String message = mEditText.getText().toString() + "\r\n";
try {
// 创建Socket
socket = new Socket("192.168.1.100", 5554); // 查看本机IP,每次开机都不同
// 向服务器发送消息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);

// 接收来自服务器的消息
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();

if (msg != null) {
mTextView.setText(msg);
} else {
mTextView.setText("数据错误!");
}
// 关闭流
out.close();
br.close();
// 关闭Socket
socket.close();
} catch (Exception e) {
// TODO: handle exception
Log.e("", e.toString());
}
}
});
}
}


2.main.xml文件简单布局
Java代码 
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent">  
    <Button android:text="Button01" android:id="@+id/Button01" 
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>  
    <TextView android:text="TextView01" android:id="@+id/TextView01" 
        android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>  
    <EditText android:text="EditText01" android:id="@+id/EditText01" 
        android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>  
</LinearLayout> 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Button01" android:id="@+id/Button01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<TextView android:text="TextView01" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:text="EditText01" android:id="@+id/EditText01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText>
</LinearLayout>

3.注意添加AndroidMenifest.xml的权限
Java代码 
<uses-permission android:name="android.permission.INTERNET" /> 

<uses-permission android:name="android.permission.INTERNET" />

4.服务器端,就是建立一个简单的java文件,运行起来就可以了
Java代码 
package cn.com;  
 
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.InputStreamReader;  
import java.io.OutputStreamWriter;  
import java.io.PrintWriter;  
import java.net.ServerSocket;  
import java.net.Socket;  
 
public class Server implements Runnable {  
    public void run() {  
        try {  
            // 创建ServerSocket  
            ServerSocket serverSocket = new ServerSocket(5554);  
            while (true) {  
                // 接受客户端请求  
                Socket client = serverSocket.accept();  
                System.out.println("accept");  
                try {  
                    // 接收客户端消息  
                    BufferedReader in = new BufferedReader(  
                            new InputStreamReader(client.getInputStream()));  
                    String str = in.readLine();  
                    System.out.println("read:" + str);  
                    // 向服务器发送消息  
                    PrintWriter out = new PrintWriter(new BufferedWriter(  
                            new OutputStreamWriter(client.getOutputStream())),  
                            true);  
                    out.println("server message");  
                    // 关闭流  
                    out.close();  
                    in.close();  
                } catch (Exception e) {  
                    System.out.println(e.getMessage());  
                    e.printStackTrace();  
                } finally {  
                    // 关闭  
                    client.close();  
                    System.out.println("close");  
                }  
            }  
        } catch (Exception e) {  
            System.out.println(e.getMessage());  
        }  
    }  
 
    // main函数,开启服务器  
    public static void main(String a[]) {  
        Thread desktopServerThread = new Thread(new Server());  
        desktopServerThread.start();  
    }  


package cn.com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable {
public void run() {
try {
// 创建ServerSocket
ServerSocket serverSocket = new ServerSocket(5554);
while (true) {
// 接受客户端请求
Socket client = serverSocket.accept();
System.out.println("accept");
try {
// 接收客户端消息
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);
// 向服务器发送消息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),
true);
out.println("server message");
// 关闭流
out.close();
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
// 关闭
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

// main函数,开启服务器
public static void main(String a[]) {
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}


以上即为所以代码,希望大家有所收获...感谢志毅的blog啊,之前写过差不多的代码没有调试成功还....
  相关解决方案