作者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