标签:android io os ar 使用 java sp 数据 on
============问题描述============
//创建监听端口..... private void StartListening() { //创建IPEndPoint IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.16.41.120"), 8897); //创建Socket实例 server_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定Socket与IPEndPoint server_Socket.Bind(ipep); //设置Socket收听模式 server_Socket.Listen(10); while (true) { try { System.Net.Sockets.Socket s = server_Socket.Accept(); Thread newsocekt= new Thread(new ParameterizedThreadStart(ServiceClient)); newsocekt.Start(s); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } //为每一个连接到服务器的套接字开辟一个新的线程 private void ServiceClient(object soc) { System.Net.Sockets.Socket clientS = soc as Socket; byte[] bytearry = new byte[1024]; int buffer_lenght = clientS.Available; clientS.Receive(bytearry, 0, buffer_lenght, SocketFlags.None);//获取安卓发来的消息,这里可以收到信息 string res = Encoding.GetEncoding("utf-8").GetString(bytearry); //****** *****/ // res 是安卓发来的消息,通过info判断做什么事情,这里省略了 byte[] arry = Encoding.GetEncoding("utf-8").GetBytes("我操你大爷,给不给我发信息回去/0"); clientS.Send(arry, arry.Length, SocketFlags.None);//往安卓回发消息 //我感觉这样写不太对,这样发到C#的客户端可以收到的,但是安卓那收不到 }
public class SocketClient { static Socket client; public SocketClient(String site, int port) { try { client = new Socket(site, port); } catch (Exception e) { Log.i("t460470591", "error"); e.printStackTrace(); } } public String sendMsg(String msg) { try { PrintWriter out; out = new PrintWriter(new BufferedWriter(new OutputStreamWriter (client.getOutputStream())), true); out.println(msg);//发送数据到服务端 Thread.sleep(1000);//没做while循环接收服务器的数据,我就直接睡眠一下,只接收一次数据 InputStream inputStream= client.getInputStream(); //获取套接字的输入流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=inputStream.read())!=-1){ //我这里DEbug发现,每次都有数据的,我就跟踪while,一个F6,F6按, //按着按着就在这里卡死了...不是我机子,我也不懂怎么弄,反正数据就回不来,程序不是错处, //而且直接就不能调试了,估计是还在等在数据 baos.write(i); } Log.i("t460470591", baos.toString());//这里获取接收的值,但是程序阻塞在这里了 return baos.toString(); } catch (Exception e) { e.printStackTrace(); Log.i("t460470591",e.getMessage()+ "a"); } return ""; }
============解决方案1============
【急】c#服务器用套接字与android服务端互通训,要双向的,我自己写了一个,不成功,求例子,求指导,急啊
标签:android io os ar 使用 java sp 数据 on
原文地址:http://www.cnblogs.com/qibileiru/p/4041895.html