我的情景
我是基于套接字的编程或TCP等网络协议的新手。我有一个基于协议工作的服务器 - 固定长度超过TCP 。我有一个示例客户端应用程序,它读取TXT文件并通过套接字将其发送到服务器。
我正在尝试使用一个简单的应用程序复制服务器,该应用程序通过套接字接收来自客户端的请求并响应客户端。
我的客户端和服务器应用程序如下所述。
客户端代码
String host = "localhost";
int port = 19997;
StringBuffer instr = new StringBuffer();
String TimeStamp;
System.out.println("SocketClient initialized");
try {
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.
getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
TimeStamp = new java.util.Date().toString();
String process = "01234"+ (char) 13;
osw.write(process);
osw.flush();
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
int c,d=0;
try
{
if(isr.ready())
{
}
else
System.out.println("NO RESPONSE");
while (( (c = isr.read()) != 13) && d<4)
{
instr.append( (char) c);
System.out.println("Inside Loop - "+instr);
d++;
}}
catch(OutOfMemoryError e)
{
System.out.println("OOM ERROR - "+e);
System.out.println(instr);
}
/** Close the socket connection. */
connection.close();
System.out.println(instr);
}
catch(UnknownHostException e)
{
System.out.println("Unknown Host Exception: " + e);
}
catch(ConnectException e)
{
System.out.println("ConnectException: " + e);
}
catch(Exception e1)
{
System.out.println("Exception: " + e1);
}
服务器端代码
try{
socket1 = new ServerSocket(port);
System.out.println("SingleSocketServer Initialized");
int character;
while (true) {
connection = socket1.accept();
BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(is);
process = new StringBuffer();
while((character = isr.read()) != 13) {
process.append((char)character);
System.out.println("Inside while loop");
}
System.out.println("Hello"+process);
//need to wait 10 seconds for the app to update database
try {
Thread.sleep(10000);
}
catch (Exception e){}
TimeStamp = new java.util.Date().toString();
//String returnCode = "SingleSocketServer repsonded at "+ TimeStamp + (char) 13;
String returnCode = "56789"+ (char) 13;
BufferedOutputStream os = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
osw.write(returnCode);
osw.flush();
}
}
catch (IOException e) {}
try {
connection.close();
}
catch (IOException e) {}
}
这很好用。
我的问题是
我已经实现了,这是 - 固定长度超过TCP?如果没有,如何实现样本客户端和服务器java应用程序?
TCP上的固定长度与我实施的相比有何不同?