采用UDP协议做个手机和电脑通讯的聊天小工具

近日研究了一下基于udp协议的网络信息交互,经过测试功能上可以实现手机和服务器之间的消息交互,基于此其实是可以实现一个聊天的软件的。先看一下效果图:

手机端(安卓)

通过上图可以发现,安卓端是作为客户端,先本地创建client,然后向服务端指定端口发送消息,同时也接收服务端发来的消息。

服务端(windows)

通过上图:服务端启动指定端口监听,当收到消息后,可以向客户端发送消息

代码:

安卓端主要代码如下:

package com.sdzyhc.udpclient;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Call;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.sdzyhc.udpsockets.Callback;
import com.sdzyhc.udpsockets.RevInterface;
import com.sdzyhc.udpsockets.UdpSockets;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "udpclient";
EditText
etrets;
EditText
etsend;
private UdpSockets mUdpsockets;
private int udpClientID = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main);
etrets=(EditText)findViewById(R.id.Rets);
etsend=(EditText)findViewById(R.id.etSend);
mUdpsockets = new UdpSockets(getApplicationContext(), new RevInterface() {
@Override
public void rev(String args) {
etrets.setText(String.valueOf(args));//接收服务端发来的消息
}
});
}
//创建客户端
public void createUdpClient(View view) {
udpClientID ++;
mUdpsockets.createSocket(udpClientID);
mUdpsockets.bind(udpClientID, 5555, "0.0.0.0", new Callback() {
@Override
public void invoke(Object... args) {
Log.
d(TAG, "bind success");
}
});
}
//发送消息
public void sendMessage(View view) {
String searchStr =
etsend.getText().toString();
String str = Base64.
encodeToString(searchStr.getBytes(), Base64.DEFAULT);
Log.
d(TAG, "send str:"+str);
mUdpsockets.send(udpClientID, str, 6666, "192.168.1.31", new Callback() {
@Override
public void invoke(Object... args) {
Log.
d(TAG, "send success");
}
});
}
//关闭客户端
public void closeUdpClient(View view) {
mUdpsockets.close(udpClientID, new Callback() {
@Override
public void invoke(Object... args) {
Log.
d(TAG, "close success");
}
});
}
}

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<
Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:onClick="createUdpClient"
android:text="启动客户端"
/>
<
EditText
android:id="@+id/etSend"
android:layout_width="match_parent"
android:layout_height="50dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
android:text="hello"
/>
<
Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:onClick="sendMessage"
android:text="发送消息"
/>
<
TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="接收数据:"
/>
<
EditText
android:id="@+id/Rets"
android:layout_width="match_parent"
android:layout_height="90dp"
android:ems="10"
android:gravity="start|top"
android:inputType="textMultiLine"
/>
<
Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:onClick="closeUdpClient"
android:text="关闭UDP客户端"
/>
LinearLayout>

服务端采用的C#编写的,代码如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.Net.Sockets;

using System.Net;

using System.Threading;

namespace UdpServer

{

public partial class Form1 : Form

{

String clientip="";

public Form1()

{

InitializeComponent();

CheckForIllegalCrossThreadCalls = false;

}


private void label1_Click(object sender, EventArgs e)

{

string ip = IPAddress.Any.ToString();

textBox1.Text = ip;

}

Socket server;

private void button1_Click(object sender, EventArgs e)

{

//

server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

//

IPAddress iP = IPAddress.Parse(textBox1.Text);

IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));


server.Bind(endPoint);

listBox1.Items.Add("服务器已经成功开启!");


Thread t = new Thread(ReciveMsg);

t.IsBackground = true;

t.Start();

}

///

/// 发送消息

///

void SendMsg()

{


String cliip = "", cliport = "";

if (!String.IsNullOrEmpty(clientip))

{

String[] arr = clientip.Split(':');

cliip = arr[0];

cliport = arr[1];

}

EndPoint point = new IPEndPoint(IPAddress.Parse(cliip), int.Parse(cliport));

string msg = textBox3.Text;

server.SendTo(Encoding.UTF8.GetBytes(msg), point);

}

///

/// 接收消息

///

void ReciveMsg()

{

while (true)

{

EndPoint point = new IPEndPoint(IPAddress.Any, 0);

byte[] buffer = new byte[1024 * 1024];

int length = server.ReceiveFrom(buffer, ref point);

string message = Encoding.UTF8.GetString(buffer, 0, length);

clientip = point.ToString();

listBox1.Items.Add(clientip + ":" + message);

textBox4.Text = clientip;

}

}

private void button2_Click(object sender, EventArgs e)

{

if (textBox3.Text != "") {


Thread t2 = new Thread(SendMsg);

t2.Start();

}

}


}

}

布局界面

以上就是这些内容,主要用于功能介绍,要想做个真正的聊天工具,还有大量工作要做,这个作为小型公司内部使用应该还可以的。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章