作者fiend1212 (依舊是帥氣小禹)
看板C_Sharp
標題[問題] Socket接收訊息時只收的到第一個字元
時間Tue Aug 3 23:22:02 2010
請問一下
我想用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
1F:→ help0430:你java是用鍵盤輸入要傳送的資料喔?那一次一個字沒錯啊 08/05 15:29
2F:→ fiend1212:可是我打clientOutput.writeBytes("HI"); 08/05 17:09
3F:→ fiend1212:也是只收的到"H"耶 08/05 17:10
4F:→ fiend1212:那為什麼用鍵盤輸入會一次一個字呢?? 08/05 17:11
5F:推 JlTsai:有一直在收嗎?? 08/05 20:32
6F:→ fiend1212:C#那邊改用stream就可以了...謝謝 08/05 20:44