[問題] Socket接收訊息時只收的到第一個字元

看板C_Sharp作者 (依舊是帥氣小禹)時間14年前 (2010/08/03 23:22), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
請問一下 我想用C# client端和JAVA Server端進行連線 在建立連線後...C#會先傳訊息給JAVA 這時JAVA收到的訊息很正常完整 接著JAVA要回傳訊息給C# 但C#卻都只收得到第一個字元耶...請問是什麼原因嗎? (例如回傳 "HELLO" 在C#只收得到 "H" ) C#的code: Console.Write("請輸入連線主機IP:"); temp = Console.ReadLine(); IPAddress ip = IPAddress.Parse(temp); IPEndPoint remote = new IPEndPoint(ip,7654); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); Console.Write("請輸入妳要傳送的字串:"); temp = Console.ReadLine(); sender.Connect(remote); byte[] msg = Encoding.UTF8.GetBytes(temp+"\0"); int bytesSent = sender.Send(msg); byte[] data = new byte[1024]; bytesSent = sender.Receive(data); temp += Encoding.UTF8.GetString(data,0,bytesSent); Console.Write("{0}\n",temp); JAVA的code: System.out.println("Waiting for a connection on port ."); serverSock = new ServerSocket(7654); connectionSock = serverSock.accept(); System.out.println("Connection from Client IP: " + connectionSock.getInetAddress().getHostAddress()); String abc = connectionSock.getInetAddress().getHostAddress(); clientInput = new DataInputStream(connectionSock.getInputStream()); clientOutput = new DataOutputStream(connectionSock.getOutputStream()); int ch = 0; StringBuffer sa = new StringBuffer(); char id; while ((id = (char)clientInput.read()) != '\0') { sa.append(id); } String id2 = sa.toString(); System.out.println(id2); Scanner keyboard = new Scanner(System.in); clientOutput.writeBytes(keyboard.next()); clientInput.close(); clientOutput.close(); connectionSock.close(); serverSock.close(); -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.71.8.243

08/05 15:29, , 1F
你java是用鍵盤輸入要傳送的資料喔?那一次一個字沒錯啊
08/05 15:29, 1F

08/05 17:09, , 2F
可是我打clientOutput.writeBytes("HI");
08/05 17:09, 2F

08/05 17:10, , 3F
也是只收的到"H"耶
08/05 17:10, 3F

08/05 17:11, , 4F
那為什麼用鍵盤輸入會一次一個字呢??
08/05 17:11, 4F

08/05 20:32, , 5F
有一直在收嗎??
08/05 20:32, 5F

08/05 20:44, , 6F
C#那邊改用stream就可以了...謝謝
08/05 20:44, 6F
文章代碼(AID): #1CM3GTSE (C_Sharp)