在Android中建立Socket用戶端(實現線上聊天室)

來源:互聯網
上載者:User

標籤:android   socket   伺服器   網路   

下面實現安卓作為用戶端實現網路聊聊天室的執行個體:

建立安卓用戶端:

<p> </p><p>package com.example.mysocketclient;</p><p>import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.Socket;import java.net.UnknownHostException;import java.util.Date;</p><p>import android.support.v7.app.ActionBarActivity;import android.support.v7.app.ActionBar;import android.support.v4.app.Fragment;import android.os.AsyncTask;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import android.os.Build;</p><p>public class MainActivity extends ActionBarActivity {</p><p> private EditText edit, edit_content; private TextView content; private Button test, send;</p><p> @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  this.edit = (EditText) super.findViewById(R.id.edit);  this.edit_content = (EditText) super.findViewById(R.id.edit_content);  this.content = (TextView) super.findViewById(R.id.show);  this.test = (Button) super.findViewById(R.id.test);  this.send = (Button) super.findViewById(R.id.fasong);</p><p>  this.test.setOnClickListener(new Test());  this.send.setOnClickListener(new Send());</p><p> }</p><p> private class Test implements OnClickListener {</p><p>  @Override  public void onClick(View arg0) {</p><p>   connect();  }</p><p> }</p><p> private class Send implements OnClickListener {</p><p>  @Override  public void onClick(View arg0) {</p><p>   send();  }</p><p> }</p><p> // ----------------------------------------</p><p> Socket socket = null; BufferedWriter writer = null; BufferedReader reader = null;</p><p> public void connect() {</p><p>    // 線程式控制制當前資料的讀寫  AsyncTask<Void, String, Void> read = new AsyncTask<Void, String, Void>() {</p><p>   @Override   protected Void doInBackground(Void... arg0) {    try {     socket = new Socket(MainActivity.this.edit.getText()       .toString(), 12345);     writer = new BufferedWriter(new OutputStreamWriter(       socket.getOutputStream()));     reader = new BufferedReader(new InputStreamReader(       socket.getInputStream()));     publishProgress("@success");    } catch (UnknownHostException e1) {     Toast.makeText(MainActivity.this, "無法串連伺服器!",       Toast.LENGTH_SHORT).show();     e1.printStackTrace();    } catch (IOException e1) {     Toast.makeText(MainActivity.this, "無法串連伺服器!",       Toast.LENGTH_SHORT).show();     e1.printStackTrace();    }    try {     String lineString = null;     while ((lineString = reader.readLine()) != null) {      publishProgress(lineString);</p><p>     }    } catch (IOException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }    return null;   }</p><p>   @Override   protected void onProgressUpdate(String... values) {    if(values[0].equals("@success")){     Toast.makeText(MainActivity.this, "串連到伺服器!", Toast.LENGTH_SHORT).show();     }    </p><p>    content.append("別人說:"+values[0]);    super.onProgressUpdate(values);   }</p><p>  };</p><p>  read.execute();</p><p> }</p><p> public void send() {  try {   content.append("我說:"+edit_content.getText().toString()+"\n");   writer.write(edit_content.getText().toString()+"\n");   writer.flush();   edit_content.setText("");  } catch (IOException e) {   // TODO Auto-generated catch block   e.printStackTrace();  } }</p><p>}</p><p> </p>


布局檔案:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TableLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TableRow>            <EditText                android:id="@+id/edit"                android:layout_width="200dp"                android:layout_height="wrap_content"                android:text="10.0.2.2" />            <Button                android:id="@+id/test"                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="串連測試" />        </TableRow>    </TableLayout>    <TextView        android:id="@+id/show"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="" />    <EditText        android:id="@+id/edit_content"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="請在這裡輸入聊天內容" />    <Button        android:id="@+id/fasong"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="發送訊息" /></LinearLayout>


首先運行上節寫的伺服器程式,然後運行安卓用戶端,點擊串連測試如下:

 

運行兩個安卓虛擬機器如下:

 

可以實現線上即時聊天了。

代碼如下:

http://download.csdn.net/detail/yayun0516/8624193

 

http://download.csdn.net/detail/yayun0516/8624199

在Android中建立Socket用戶端(實現線上聊天室)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.