socket问题,很简单,有懂的帮忙解决下.(100分)

  • 主题发起人 主题发起人 jack_fang
  • 开始时间 开始时间
J

jack_fang

Unregistered / Unconfirmed
GUEST, unregistred user!
服务器端发来数据,前2字节是标志这个包的大小,我接收端应该怎么写?
procedure TForm1.ClientSocketRead(Sender: TObject;
Socket: TCustomWinSocket);
var
len:word;
buf:array of char;
msg:string;
begin
try
memo1.Lines.Add(inttostr(socket.ReceiveLength));
Socket.ReceiveBuf(len, 2);
memo1.Lines.Add('len:' + inttostr(len));
if len < 1 then Exit;
setlength(buf, len);
Socket.ReceiveBuf(buf[0], len);
setlength(msg, len);
Move(buf[0], msg[1], len);
MemReadMsg.Lines.Add(msg);
except
end;

end;

怎么得到前2个字节
 
今天正搞socket编程,delphi做客户端,java做服务端,不知道有谁处理过类似的没?
顶一下
 
var
Size: DWORD;
RSize: PWORD;
Buf: PChar;
Msg: string;
begin
Size:= ClientSocket1.Socket.ReceiveLength;
GetMem( Buf, Size );
ClientSocket1.Socket.ReceiveBuf( Buf, Size );
RSize:= @Buf[0]; //取接收过来的包大小
SetLength( Msg, Size - 2 );
Move( Buf[2], msg[1], Size - 2 ); //获得包的内容
FreeMem( Buf );
end;
 
1.客户端发送数据。
2。服务器端接受数据。
我用IdTCPServer做过,你用SOCKET应该是类似的。
关键语句如下:
resiveString,outString:string;
resiveString:=AThread.Connection.AllData;
if (ord(resiveString[1])=$0E)//这一句是我在判断接受到的第一个字节的字符的ASCII码是不是等于十六进制的0E。。。

下面的是我JAVA服务器端一部分代码:
package servebank;

import java.io.*;
import java.net.*;
import com.dareway.util.*;
import java.util.*;

/**
* 处理一个客户端的线程
*/
public class ServerThread
extends Thread {

private Socket socket;
private InputStream in;
private OutputStream out;

public ServerThread(Socket s) throws IOException {
this.socket = s;
// this.socket.setSoTimeout(1000000);
// this.socket.setReceiveBufferSize(99999999);
this.in = this.socket.getInputStream();
this.out = this.socket.getOutputStream();
this.start();
}

public void run() {
try {
while (true) {
//接收数据,第8-17位表示此次传递数据的长度
byte[] bytesIn = new byte[17];
if (this.in.read(bytesIn) != 17) {
break;
}
StringBuffer paraStr = new StringBuffer();
String paramStr = new String(bytesIn);

String sjzc = paramStr.substring(7, 17); //数据总长
String jym = paramStr.substring(0, 4); //交易码
Log4j.debug(this, "交易码:" + jym);
Log4j.debug(this, "数据总长:" + sjzc);
int length = Integer.parseInt(sjzc.trim());
byte[] bytesHead = new byte[44]; //包头剩余字节
if (this.in.read(bytesHead) != 44) {
break;
}
String paramHead = new String(bytesHead);
paramStr += paramHead;
paraStr.append(paramStr);
if ("2009".equals(jym)) { //对2009交易单独处理
byte [] bys = new byte [length-61];
for (int i = 0; i < length - 61 ; i++) {
int b = in.read();
if ( b != -1){
bys=(byte)b;
}else{
break;
}
}
paraStr.append(new String(bys));
Log4j.debug(this,"数据接收完毕!");
}
else {
length = length - 61;
bytesIn = new byte[length];
if (this.in.read(bytesIn) != length) {
break;
}
// Log4j.debug(this, "数据总长:" + sjzc);
String para = new String(bytesIn);
paraStr.append(para);
}
//处理请求
byte[] bytesOut = Delegate.run(paraStr.toString(), this.socket);
this.out.write(bytesOut);
this.out.flush();
} //end while
}
catch (Exception ex) {
}
finally {
try {
socket.close();
}
catch (Exception ex) {
}
}
}
}
 
后退
顶部