我试图通过Wifi通过TCP连接将数据从C#.NET(Windows应用程序)程序发送到Java(Android App)程序,反之亦然。到目前为止,我已成功将数据从Java发送到C#,但无法从C#发送到Java。
以下是Java代码,我用来创建连接并接收数据:
ServerSocket serverSocket = null;
DataInputStream socketInputStream;
while (true) {
try {
String localIPAddr = getLocalIPAddress();
InetSocketAddress ipEndPoint = new InetSocketAddress(
InetAddress.getByName(localIPAddr), 8222);
serverSocket = new ServerSocket();
serverSocket.bind(ipEndPoint, 4);
workerSocket = serverSocket.accept();
socketInputStream = new DataInputStream(
workerSocket.getInputStream());
inputText.setText(socketInputStream.readUTF());
} catch (Exception ex) {
throw ex;
}
}
此处getLocalIPAddress()
方法返回Android设备的IP地址。
以下是Windows应用程序中的C#代码,用于连接到Android的IP地址(192.168.1.6)并向其发送数据:
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
void button1_Click(object sender, EventArgs e)
{
try
{
if (!clientSocket.Connected)
clientSocket.Connect(IPAddress.Parse("192.168.1.6"), 8222);
clientSocket.Send(Encoding.UTF8.GetBytes(txtInput.Text));
}
catch (Exception ex)
{
throw ex;
}
}
嗯,客户端(C#)无法连接到服务器(Java)这意味着数据不会从客户端离开。但它会,如果它连接起来的话。请告诉我我错过了什么,我在哪里弄错了。 :)
答案 0 :(得分:1)
启动Android应用程序并连接到wifi后,您是否尝试对启动应用程序的IP执行ping操作。
ping 192.168.1.6
如果可以从运行C#app的工作站访问IP,请尝试在android ip的IP和端口上执行telnet,以查看它是否有效。
telnet 192.168.1.6 8222
如果两个步骤中的任何一个失败,则可能是wifi网络中的问题。正如我多次注意到路由器的防火墙过滤掉除8080和80之外的所有端口。因此您需要打开路由器上的端口。
答案 1 :(得分:0)
你试过这个吗?
Runnable showmessage = new Runnable() {
public void run() {
myTextView.setText(membervariabletext);
}
};
从你的线程中,在readUTF()之后,调用
runOnUiThread(showmessage);
答案 2 :(得分:0)
嗯,我自己解决了这个问题,但当然Dilberted对我有所帮助。我感谢他所提供的一切。 :)
查看下面解决的Java代码:
ServerSocket serverSocket = null;
Socket workerSocket;
DataInputStream socketInputStream;
try {
if (serverSocket == null) {
// No need to get local IP address and to bind InetSocketAddress.
// Following single line make it very simple.
serverSocket = new ServerSocket(8222, 4);
workerSocket = serverSocket.accept();
}
// When data are accepted socketInputStream will be invoked.
socketInputStream = new DataInputStream(
workerSocket.getInputStream());
/* Since data are accepted as byte, all of them will be collected in the
following byte array which initialised with accepted data length. */
byte[] rvdMsgByte = new byte[socketInputStream.available()];
// Collecting data into byte array
for (int i = 0; i < rvdMsgByte.length; i++)
rvdMsgByte[i] = socketInputStream.readByte();
// Converting collected data in byte array into String.
String rvdMsgTxt = new String(rvdMsgByte);
// Setting String to the text view.
receivedMsg.setText(rvdMsgTxt);
} catch (Exception ex) {
throw ex;
}
请注意,将使用单独的线程在后台运行此代码。