服务端代码
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.text.*;
public class server
{
private static String getInputMsg( Socket s )
{
String inStr = "";
if(s == null)
return inStr;
try{
InputStream in = s.getInputStream();
byte[] inStrBuff = new byte[1024];
in.read(inStrBuff);
inStr = new String(inStrBuff);
}
catch(IOException e)
{
e.printStackTrace();
}
return inStr.trim();
}
private static void sendOutputMsg(Socket s, String msg)
{
if( s == null || msg == "" )
return;
try{
OutputStream out = s.getOutputStream();
out.write( msg.getBytes() );
out.flush();
}
catch(IOException e)
{
e.printStackTrace();
}
}
private static String getCurrentTime()
{
//get now time string
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("yyyyMMddhhmmss");
String nowTime = new String(ft.format(dNow));
return nowTime;
}
public static void main(String [] args)
{
try{
//listen at port 10086
ServerSocket serverSocket = new ServerSocket(10086);
System.out.println( "start listen at port 10086" );
while(true)
{
//accept
Socket server = serverSocket.accept();
//print client message
String clientMsg = getInputMsg(server);
System.out.println( "data from client => " + clientMsg );
//create response data send to client
System.out.println("client data length = " + clientMsg.length());
String msg = "$ST$" + getCurrentTime() + "0000" + "RECE" + "0000" + "$ED$";
sendOutputMsg(server, msg);
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
客户端代码
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.text.*;
public class client
{
private static String getInputMsg( Socket s )
{
String inStr = "";
if(s == null)
return inStr;
try{
InputStream in = s.getInputStream();
byte[] inStrBuff = new byte[1024];
in.read(inStrBuff);
inStr = new String(inStrBuff);
}
catch(IOException e)
{
e.printStackTrace();
}
return inStr.trim();
}
private static void sendOutputMsg(Socket s, String msg)
{
if( s == null || msg == "" )
return;
try{
OutputStream out = s.getOutputStream();
out.write( msg.getBytes() );
out.flush();
}
catch(IOException e)
{
e.printStackTrace();
}
}
private static String getCurrentTime()
{
//get now time string
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("yyyyMMddhhmmss");
String nowTime = new String(ft.format(dNow));
return nowTime;
}
public static void main(String [] args)
{
try{
Socket client = new Socket("127.0.0.1",10086);
//send message to server
String msg = "$ST$" + getCurrentTime() + "0000" + "STAT" + "0000" + "$ED$";
sendOutputMsg(client, msg);
//print server message
String serverMsg = getInputMsg(client);
System.out.println("server data length = " + serverMsg.length());
System.out.println( "data from server => " + serverMsg );
}
catch(IOException e)
{
e.printStackTrace();
}
}
}