Android开发客户端与Eclipse服务端通信聊天例子

释放双眼,带上耳机,听听看~!

看一下实现的效果:点击建立连接与连接服务器,(因为没做优化,所以要先点击连接才能点击其他按钮,不然软件会奔溃)

 

一、首先是Eclipse服务端的代码

1、创建一个ServerTest类,实现如下代码:

自定义端口号为10086,做循环接收操作,并开启新线程。

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ServerSocket serverSocket=new ServerSocket(10086);
while(true) {
Socket socket=serverSocket.accept();//阻塞
new Thread(new ServerImp(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

1、创建一个ServerImp类,继承线程,实现如下代码:

如果客户端发送消息1314520过来的话就断开连接

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
public class ServerImp implements Runnable {
private Socket socket;
private PrintWriter printWriter;
private BufferedReader bufferedReader;
private String receiverMsg = "";
public ServerImp(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
System.out.println("建立连接");
try {
printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")),
true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
printWriter.println("建立连接成功");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
if ((receiverMsg = bufferedReader.readLine()) != null) {
if (receiverMsg.equals("1314520")) {
printWriter.println("断开连接成功");
System.out.println("客户端请求断开连接成功");
printWriter.close();
bufferedReader.close();
break;
}else {
System.out.println("客户端:"+receiverMsg);
printWriter.println("服务器:受到了您的消息--"+receiverMsg);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

3、服务端的代码做好了,运行ServerTest类。

二、AndroidStudio客户端的代码

1、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/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入发送给服务器的信息"
android:padding="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="connect"
android:text="建立连接" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="send"
android:text="发送消息" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="disconnect"
android:text="断开连接" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="" />
</ScrollView>
</LinearLayout>

2、建一个工具类

package com.shopping.cxb.chatclient;
/**
* Created by LYB on 2018/4/25.
* 判断是否为空的工具类
*/
public class IsEntityUtils {
public static boolean isEntityString(String entity) {
if (entity == null || entity.length() == 0 || entity.equals(""))
return true;
return false;
}
}

 

3、MainActivty代码实现

package com.shopping.cxb.chatclient;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private EditText mEditText;
private TextView mTextView;
private static final String HOST = "192.168.253.1";
private static final int PORT = 10086;
private Socket socket;
private PrintWriter printWriter;
private BufferedReader bufferedReader;
private String receiveString = "";
private StringBuffer stringBuffer;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mTextView.setText(stringBuffer.append(receiveString+"n"));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditText = findViewById(R.id.editText);
mTextView = findViewById(R.id.textView);
}
/**
* 循环接受数据方法
*/
public void receviceMsg() {
stringBuffer = new StringBuffer();
while (true) {
try {
if (!IsEntityUtils.isEntityString(receiveString=bufferedReader.readLine())) {
handler.sendEmptyMessage(1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 建立连接
*/
class ConnectRun implements Runnable {
@Override
public void run() {
try {
socket = new Socket(HOST, PORT);
printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
receviceMsg();
} catch (IOException e) {
Log.e("111", e.toString());
e.printStackTrace();
}
}
}
/**
* 发送信息
*/
class SendRun implements Runnable {
@Override
public void run() {
printWriter.println(mEditText.getText().toString());
}
}
/**
* 断开连接
*/
class disconnectRun implements Runnable {
@Override
public void run() {
printWriter.println("1314520");
if (printWriter!=null){
printWriter.close();
}
if (bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 点击建立连接按钮
*
* @param view
*/
public void connect(View view) {
new Thread(new ConnectRun()).start();
}
/**
* 点击发送消息按钮
*
* @param view
*/
public void send(View view) {
new Thread(new SendRun()).start();
}
/**
* 点击断开连接按钮
*
* @param view
*/
public void disconnect(View view) {
new Thread(new disconnectRun()).start();
}
}

4、完成,允许客户端发送信息。

源码下载链接:https://download.csdn.net/download/weixin_39001306/10444180

人已赞赏
Android文章

Android开发Browser配置管理(深入了解)

2020-1-30 15:47:28

Android文章

Android开发实现摇动/抖动动画的方法

2020-1-30 18:18:27

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索