我是套接字编程的新手。我想用C#创建一个PC应用程序,一个Android手机应用程序可以通过无线网络(LAN)与其他人通信。
为了向Android应用程序发送数据,我在PC端使用此代码:
private void sendButton_Click(object sender, EventArgs e)
{
try
{
Object objData = messageTextBox.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
_socket.Send (byData);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.18"), 2001);
_socket.Connect(_ipEndPoint);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
在Android应用中,我希望使用以下代码接收数据:
Handler myUpdateHandler = new Handler()
{
public void handleMessage(Message msg)
{
Log.d(appTag, "setting textview");
TextView tv = (TextView) findViewById(R.id.messageText);
tv.setText(mClientMsg);
}
};
class CommsThread implements Runnable
{
public void run()
{
try
{
Socket s = null;
try
{
ss = new ServerSocket(2001);
}
catch (IOException e)
{
Log.d(appTag, e.toString());
}
while (!Thread.currentThread().isInterrupted())
{
Message m = new Message();
Log.d(appTag, "message m = new message()");
try
{
if (s == null) s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
Log.d(appTag, line);
mClientMsg = line;
}
myUpdateHandler.sendMessage(m);
}
catch (IOException e)
{
Log.d(appTag, e.toString());
}
}
}
catch (Exception e)
{
Log.d(appTag, e.toString());
}
}
}
但Android应用程序不会收到任何数据。
任何人都可以帮我解决我的问题吗? 我在套接字编程方面非常棒。
抱歉英语不好。 感谢。答案 0 :(得分:0)
如果您更新阅读器只是阅读字符并将其吐出来,它会显示什么? e.g。
try
{
if (s == null) s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
char[] recvd = new char[1];
while (in.read(recvd, 1, 1) != -1)
{
String line = new String(recvd);
Log.d(appTag, line);
mClientMsg = line;
}
myUpdateHandler.sendMessage(m);
}
catch (IOException e)
{
Log.d(appTag, e.toString());
}