定義scoket和字符輸入輸出流
Socket socket =new Socket(InetAddress.getName(str),6789);
//新建scoket 參數(shù)是IP地址和端口號(hào)
PrintWriter out=new PrintWriter(socket.getOutputStream);
//根據(jù)outputstream實(shí)例生成PrintWriter實(shí)例
/**java是unicode編碼蒋得,是雙字節(jié)的
Reader用于字符的讀(字符數(shù)據(jù)的輸入) Writer用于字符的讀(字符數(shù)據(jù)的輸出)
而InputStream 是輸入流(外部文件輸入內(nèi)存) read方法 從輸入流讀取
outputStream輸出流(內(nèi)存輸出到文件) write 寫入該輸出流
*/
讀取數(shù)據(jù)到內(nèi)存所以是輸入
寫數(shù)據(jù)是內(nèi)存輸出到文件
BufferReader in=new BufferReader(new InputStream(socket.getInputStream, "utf-8"));
//字節(jié)流轉(zhuǎn)換成字符流 BufferReader 設(shè)置編碼格式
字節(jié)流是原始數(shù)據(jù)径缅,用戶讀入后需要進(jìn)行相應(yīng)的編碼轉(zhuǎn)換 字符流是自動(dòng)轉(zhuǎn)換的
Gson
Gson gson=new Gson();
While(true){
Map map=new HashMap();
map.put("ceshi","ok");
map.put("imei",str);//key+value
String back=gson.toJson(map);//利用gson將map(或Java對(duì)象)轉(zhuǎn)換為json字符串
out.println(back);//打印該字符串
out.flush();//刷新該流的緩沖
String getback=in.readLine();//獲取返回的字符串
Map<String,String> retmap=gson.fromJson(getback,new TypeToken<Map<String,String>>()){}.getType());
//將返回的json字符串 反序列化成map(或者Java對(duì)象)
String id=(String)retmap.get("id");
String name=(String)retmap.get("name");
String age=(String)retmap.get("age");
}
服務(wù)端 建立線程監(jiān)聽
//初始化該Socket對(duì)應(yīng)的輸入流 解決中文亂碼 使用utf-8
br = new BufferedReader(new InputStreamReader(
s.getInputStream() , "utf-8"));
out=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
sout = new PrintWriter(s.getOutputStream());
String content = null;
//采用循環(huán)不斷從Socket中讀取客戶端發(fā)送過來的數(shù)據(jù)
Gson gson =new Gson();
if ((content = readFromClient()) != null)
{
Map<String, String> retMap = gson.fromJson(content,
new TypeToken<Map<String, String>>() {
}.getType());
//將json字符串content轉(zhuǎn)換成map
if(retMap.size()==2)
{
//向手機(jī)端發(fā)送數(shù)據(jù) mapsize是key的數(shù)量
String ostr="yes";
OutputStream os = s.getOutputStream();
os.write((ostr + "\n").getBytes("utf-8"));
String jstr=(String)retMap.get("ceshi");
tring imei=(String)retMap.get("imei");
try {
//判斷當(dāng)前時(shí)間
if(jstr.equals("ok")){
//返回信息
Sqlcon scon =new Sqlcon();
Connection conn = scon.getConnection();
//Statement smt=conn.createStatement();
String sql="INSERT into dbo.Time values(?,?);";//sql語句中末尾的分號(hào)可有可無
PreparedStatement ppst=conn.prepareStatement(sql);
ppst.setString(1,imei);//對(duì)sql語句中的每個(gè)醇疼?按順序賦值,賦值的方法取決于數(shù)據(jù)庫的字段屬性,我的字段屬性都是字符串類型
Date date=new java.util.Date();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//設(shè)置顯示格式
String nowTime= df.format(date);//用DateFormat的format()方法在dt中獲取并以yyyy/MM/dd HH:mm:ss格式顯示
//System.out.println(nowTime);
ppst.setString(2, nowTime);
ppst.executeUpdate();
//System.out.println("手機(jī)端簽到成功");
//smt.close();
ppst.close();
conn.close();
out.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}