gpt4 book ai didi

c# - C#(ASP.NET)通过套接字与Android通信

转载 作者:行者123 更新时间:2023-12-03 12:09:23 25 4
gpt4 key购买 nike

我已经研究了一段时间了。我有基本概念,现在尝试实现ASP.NET和android之间的套接字通信。
我正在使用基本的Windows System.Net.Sockets来解决这个问题。我在尝试逐行调试应用程序时得到一个连接,该行告诉我服务器正在运行,但问题是C#行卡在了sender.Receive(bytes)上。

这是我的TCPServer的Android端服务器代码

public class TCPServer extends Thread {
public static final int SERVER_PORT = 11000;
private boolean running = false;
private PrintWriter mOut;
private OnMessageReceived messageListener;


public TCPServer(OnMessageReceived messageListener)
{
this.messageListener = messageListener;
}

public void sendMessage(String message)
{
if(mOut != null && !mOut.checkError())
{
mOut.println(message);
mOut.flush();
}
}

@Override
public void run()
{
super.run();
running=true;
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
Socket client = serverSocket.accept();
try {
//sends the message to the client
mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

//read the message received from client
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

//in this while we wait to receive messages from client (it's an infinite loop)
//this while it's like a listener for messages
while (running) {
String message = in.readLine();

if (message != null && messageListener != null) {

messageListener.messageReceived(message);
sendMessage("OK Message is received here");
//the line above and below is also not helping me with my problem
mOut.println("OK: FROM ACOM");
}
}
}
catch (Exception e)
{
e.getMessage();
}
finally {
client.close();
}
}
catch (Exception e)
{
e.getMessage();
}
}

public interface OnMessageReceived {
public void messageReceived(String message);
}
}

这是我从当前主要 Activity 中调用它的方式,当前使用一个简单的按钮来启动服务器以进行此类监听
btnStartServer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,"Starting the server",Toast.LENGTH_LONG).show();
TCPServer tcpServer = new TCPServer(new TCPServer.OnMessageReceived() {
@Override
public void messageReceived(String message) {
txtMessageReceived.setText(message);
}
});
tcpServer.start();

}
});

现在,对于C#或ASP.NET,我刚刚在webforms页面上添加了一个简单的按钮来进行测试,这是该代码
        IPAddress ipAddress;
IPEndPoint remoteEP;
Socket sender;
byte[] bytes;
private void setUpSockets()
{
bytes = new byte[1024];
try
{
ipAddress = IPAddress.Parse("192.168.0.102");
remoteEP = new IPEndPoint(ipAddress, 11000);
sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
byte[] msg = Encoding.ASCII.GetBytes("This is some Test <EOF>");
int byteSent = sender.Send(msg);
int byteRec = sender.Receive(bytes);
string messageRec = Encoding.ASCII.GetString(bytes, 0, byteRec);

sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (Exception e)
{
string exception = e.Message;
}
}
catch (Exception m)
{
string exception = m.Message;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
setUpSockets();
}

现在,我只是在测试它,然后再将其添加到有意义的东西中,但是我仍然停留在此 int byteRec = sender.Receive(bytes);上,我不确定应该怎么做,因为如您所见,我也在尝试从android客户端发送一些响应。就像它停留在此行等待响应,它再也没有收到,Android端的文本框也没有更新收到的任何内容。

最佳答案

我一直在尝试找到正确的方法来执行此操作,但是问题是我需要确保两种语言的编码,并确保在接收数据之前在任一侧都接收字节。
This
这个问题非常有帮助,我能够使代码正常工作

进行了以下更改并奏效

C#面

 bytes = new byte[1024];
try
{
ipAddress = IPAddress.Parse("192.168.0.128");
remoteEP = new IPEndPoint(ipAddress, 11000);
sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
string toSend = TextBox1.Text;

sender.Connect(remoteEP);
//sending
int toSendLen = System.Text.Encoding.ASCII.GetByteCount(toSend);
byte[] toSendBytes = System.Text.Encoding.ASCII.GetBytes(toSend);
byte[] toSendLenBytes = System.BitConverter.GetBytes(toSendLen);
//Console.WriteLine("Soccket connected to{0}", sender.RemoteEndPoint.ToString());
sender.Send(toSendLenBytes);
sender.Send(toSendBytes);

//Receiving

byte[] rcvLenBytes = new byte[4];
sender.Receive(rcvLenBytes);
int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0);
byte[] rcvBytes = new byte[rcvLen];
sender.Receive(rcvBytes);
String rcv = System.Text.Encoding.ASCII.GetString(rcvBytes);
TextBox1.Text = rcv;


//----------------OLD----------------------------
// byte[] msg = Encoding.ASCII.GetBytes("This is some Test.");
// TextBox1.Text = msg.ToString();
// int byteSent = sender.Send(msg);
// TextBox1.Text += "Bytes Sent = " + byteSent;

//// System.Threading.Tasks.Task.Delay(1000).Wait();
// int byteRec = sender.Receive(bytes);
// string messageRec = Encoding.ASCII.GetString(bytes, 0, byteRec);
// Console.WriteLine("Response from remote Device {0}", messageRec);
// TextBox1.Text += "\nmessageRec = " + messageRec;
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
catch (Exception m)
{
Console.WriteLine(m.Message);
}

Android Side
        ServerSocket serverSocket = new ServerSocket(11000, 10);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();

// Receiving
byte[] lenBytes = new byte[4];
is.read(lenBytes, 0, 4);
int len = (((lenBytes[3] & 0xff) << 24) | ((lenBytes[2] & 0xff) << 16) |
((lenBytes[1] & 0xff) << 8) | (lenBytes[0] & 0xff));
byte[] receivedBytes = new byte[len];
is.read(receivedBytes, 0, len);
String received = new String(receivedBytes, 0, len);
// Sending
String toSend = "Echo: " + received;
byte[] toSendBytes = toSend.getBytes();
int toSendLen = toSendBytes.length;
byte[] toSendLenBytes = new byte[4];
toSendLenBytes[0] = (byte)(toSendLen & 0xff);
toSendLenBytes[1] = (byte)((toSendLen >> 8) & 0xff);
toSendLenBytes[2] = (byte)((toSendLen >> 16) & 0xff);
toSendLenBytes[3] = (byte)((toSendLen >> 24) & 0xff);
os.write(toSendLenBytes);
os.write(toSendBytes);

socket.close();
serverSocket.close();

上面提到的android代码已在方法运行的TCPServer类中更新。

关于c# - C#(ASP.NET)通过套接字与Android通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43819505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com