您的位置:首页 > 移动开发 > 微信开发

基于安卓的c/s模式的聊天小程序

2015-06-10 22:16 531 查看
欢迎交流,转载请注明出处: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  安卓 聊天程序 tcp-ip