手机与PC的网络协议(1)(3)
和客户端线程,也就是刚才说的子线程代码:
- ackage com.example.eetalk;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import android.os.Handler;
- import android.os.Message;
- public class ClientThread extends Thread {
- private Handler handler;
- private DataOutputStream dos;
- private DataInputStream dis;
- private Socket socket;
- public ClientThread(Handler handler) {
- this.handler = handler;
- }
- public void run() {
- try {
- connect();
- dos.writeInt(1);
- dos.writeInt(5);
- dos.write("hello".getBytes());
- while (true) {
- //读取服务器发过来的数据
- int msgType = dis.readInt();
- //
- System.out.println("121");
- //
- int len = dis.readInt();
- //
- byte[] bytes = new byte[len];
- dis.readFully(bytes);
- //
- String content = new String(bytes, "GB2312");
- Message msg = new Message();
- msg.what = 1;
- //
- msg.obj = content;
- //
- handler.sendMessage(msg);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- //close();
- }
- }
- private void connect() throws UnknownHostException, IOException {
- //
- socket = new Socket("172.27.35.3", 8888);
- //
- dis = new DataInputStream(socket.getInputStream());
- dos = new DataOutputStream(socket.getOutputStream());
- }
- private void close() {
- if (dis != null) {
- try {
- dis.close();
- } catch (IOException e) {
- }
- }
- if (dos != null) {
- try {
- dos.close();
- } catch (IOException e) {
- }
- }
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- }
- }
- }
- //发送到服务器的
- public boolean sendText(String content){
- try {
- //
- byte[] bytes = content.getBytes("GB2312");
- //
- dos.writeInt(1);
- //
- dos.writeInt(bytes.length);
- //
- dos.write(bytes);
- dos.flush();
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
- }
记住你的手机和你的电脑一定要在同一个局域网,这里可以看出手机的客户端做法与电脑是差不多的,上面手机客户端连接的ip地址是你的电脑连入的ipv4地址,可以在cmd命令里恰如ipconfig来搜寻。
做到这里,将你的app下载到手机,打开服务器,打开手机的应用程序,就可以聊天了,记住打开网络
美美聊天了:
这是服务器
这是手机客户端
做到这里,就可以和手机互发图片和文字啦,这是小编下期的实现目标 。
评论暂时关闭