Android客户端通过socket与服务器通信

android端--Client

package com.sec.chatroomandroid;

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.os.StrictMode;
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 MainActivity extends Activity
{
private final String DEBUG_TAG = "Activity01"; 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)
{
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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("172.16.29.201",5000);
//向服务器发送消息
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(DEBUG_TAG, e.toString());
}
}
});
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sec.chatroomandroid"
android:versionCode="1"
android:versionName="1.0" > <uses-permission android:name="android.permission.INTERNET"/> <uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>

布局文件--activity_main

<?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"
>
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Message_Recv"
/>
<EditText
android:id="@+id/EditText01"
android:hint="@string/Message_Send"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<Button
android:id="@+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/Send"
/>
</LinearLayout>

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources> <string name="app_name">ChatRoomAndroid</string>
<string name="Message_Recv">这里显示接收到服务器发来的信息</string>
<string name="Message_Send">输入要发送的内容</string>
<string name="Send">发送</string> </resources>

PC端--Server

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 ChatServer implements Runnable
{
public void run()
{
try
{
//创建ServerSocket
ServerSocket serverSocket = new ServerSocket(5000,10);
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");
}
serverSocket.close();
} }
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
//main函数,开启服务器
public static void main(String a[])
{
Thread desktopServerThread = new Thread(new ChatServer());
desktopServerThread.start();
}
}
上一篇:FacebookFriendAdderPro


下一篇:isstream例子