基于安卓的c/s模式的聊天小程序
来源:互联网 发布:常平淘宝培训 编辑:程序博客网 时间:2024/05/21 06:43
欢迎交流,转载请注明出处:http://blog.csdn.net/restaurant123/article/details/46447401
服务器端运行在电脑上:
/***Server.java*/import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.Scanner;public class Server { static DataOutputStream dos; static DataInputStream dis; public static void main(String args[]) throws Exception{ ServerSocket ss = new ServerSocket(50000); Socket socket = ss.accept(); dos = new DataOutputStream(socket.getOutputStream()); dis = new DataInputStream(socket.getInputStream()); new Thread(){ @Override public void run(){ Scanner scanner = new Scanner(System.in); while(scanner.hasNextLine()){ try { String sendString = "Server (" + CurrentTime.getCurrentTime() + ")\n" + scanner.nextLine(); dos.writeUTF(sendString); } catch (IOException e) { e.printStackTrace(); } } } }.start(); try { dos.writeUTF("您已连接上HOST的服务器"); String string = null; // while括号里面是循环条件,不是if判断条件,一旦不满足循环就结束了,两个条件不能混淆!!! while((string = dis.readUTF())!= null){ if(!string.equals("")){ System.out.println(string); } } } catch (Exception e1) { e1.printStackTrace(); } }}
/**CurrentTime.java*/import java.text.SimpleDateFormat;import java.util.Date;public class CurrentTime { public static String getCurrentTime(){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // HH是24小时制,hh是12小时制。 return simpleDateFormat.format(new Date()); }}
客户端运行在安卓手机上:
/** MainActivity.java */package com.example.chatclient;import java.net.Socket;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.EditText;public class MainActivity extends Activity { EditText hostInput; Socket socket; SharedPreferences preferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); hostInput = (EditText)findViewById(R.id.hostInput); preferences = getSharedPreferences("host", MODE_PRIVATE); editor = preferences.edit(); hostInput.setText(preferences.getString("host", "")); } public void connect(View view) { new Thread() { @Override public void run() { try { String host = hostInput.getText().toString(); editor.putString("host", host); editor.commit(); Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtra("host", host); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } }.start(); }}
/** SecondActivity.java */package com.example.chatclient;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.Socket;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.preference.Preference;import android.text.method.ScrollingMovementMethod;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ScrollView;import android.widget.TextView;import android.widget.Toast;public class SecondActivity extends Activity { TextView show; EditText input; ScrollView scrollView; Socket socket; Handler handler; StringBuffer showBuffer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); input = (EditText)findViewById(R.id.input); show = (TextView)findViewById(R.id.show); scrollView = (ScrollView) findViewById(R.id.scrollView); showBuffer = new StringBuffer(); handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what == 0x001){ showBuffer.append(msg.getData().getString("show") + "\n"); show.setText(showBuffer); // 如果聊天内容超过屏幕,ScrollView自动滚动到底部,不用再手动去下滑了。 scrollToBottom(scrollView, show); } else if(msg.what == 0x002){ showBuffer.append("Client (" + CurrentTime.getCurrentTime() + ")\n" + input.getText().toString().trim() + "\n"); show.setText(showBuffer); input.setText(""); } } }; new Thread(){ String inputString = null; @Override public void run(){ try{ String host = SecondActivity.this.getIntent().getStringExtra("host"); socket = new Socket(host, 50000); DataInputStream dis = new DataInputStream(socket.getInputStream()); // while括号里面是循环条件,不是if判断条件,一旦不满足循环就结束了,两个条件不能混淆!!! while((inputString = dis.readUTF()) != null){ if (!inputString.equals("")) { Message msg = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString("show", inputString); msg.what = 0x001; msg.setData(bundle); handler.sendMessage(msg); } } } catch(Exception e){ e.printStackTrace(); } } }.start(); } // 用来实现信息传来时,自动滑到最底部,网上找的。。 public static void scrollToBottom(final View scroll, final View inner) { Handler mHandler = new Handler();// Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached. mHandler.post(new Runnable() { public void run() { if (scroll == null || inner == null) { return; } int offset = inner.getMeasuredHeight() - scroll.getHeight(); if (offset < 0) { offset = 0; } scroll.scrollTo(0, offset); } }); } public void send(View view){ new Thread(){ @Override public void run(){ try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); String sendString = "Client (" + CurrentTime.getCurrentTime() + ")\n" + input.getText().toString().trim(); dos.writeUTF(sendString); handler.sendEmptyMessage(0x002); } catch (IOException e) { e.printStackTrace(); } } }.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }}
/** CurrentTime.java代码同上 */
<!-- activity_main.xml --><?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" > <EditText android:id="@+id/hostInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="input the Server IP" /> <Button android:id="@+id/hostSetting" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:onClick="connect" android:text="connect" /></LinearLayout>
<!-- activity_second.xml --><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.chatclient.SecondActivity" > <!-- 实现带滚动条的文本框,记住! --> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1.0" <!--Defines whether the scrollview should stretch its content to fill the viewport --> android:fillViewport="true" android:scrollbars="vertical" > <TextView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="20sp" /> </ScrollView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/input" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:selectAllOnFocus="false" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="send" android:text="send" /> </LinearLayout></LinearLayout>
参考文章:
1.
ScrollView当显示超出当前页面时自动移动到最底端 - 短裤党 - ITeye技术网站
http://gundumw100.iteye.com/blog/1162964
0 0
- 基于安卓的c/s模式的聊天小程序
- 小白基于Csocket的局域网聊天文件传输软件C/S模式
- 基于C/S模式的简单聊天程序(客户端篇)
- 基于C/S模式的简单聊天程序(服务器篇)
- 一个基于安卓的蓝牙聊天、分享照片小程序
- 基于Linux C 的简单聊天程序
- 基于HTTP长连接的B/S 聊天程序
- 基于C/S架构的聊天系统的实现
- 基于UDP协议的Java聊天小程序!
- 黑马程序员_基于Socket_UDP的聊天小程序
- 基于Java socket和多线程的简易聊天小程序
- java 基于网络编程的聊天小程序
- 基于TCP协议的Java聊天小程序
- Winform应用-简单的C/S聊天程序
- 基于silverlight的聊天程序
- 基于UDP的聊天程序
- 基于UDP的聊天程序
- [C语言]基于UDP的聊天程序模型
- Android加载图片OutOfMemery
- 欢迎使用CSDN-markdown编辑器
- ubuntu下安装opendx
- the Determine in June
- Android 判断SD卡是否存在及容量查询
- 基于安卓的c/s模式的聊天小程序
- 黑马程序员---2015.6.10java学习笔记---软件--dos--JDK---while
- ubuntu14.04下使用tetview遇到的问题
- 优雅的scala---乘法口诀表
- 树莓派--安装chromium
- Linux压缩与解压
- Optimize你的多项式计算
- apt-get安装opencv
- Linux环境变量配置文件