|
怎么我的客户端得不到返回数据呢
1 ClientSP.java
[php]
import java.io.*;
import java.net.*;
public class ClientSP
{
private void sending()
{
try
{
System.out.println("正在连接服务器...");
Socket server = new Socket(InetAddress.getLocalHost(),8383);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()))
PrintWriter out = new PrintWriter(server.getOutputStream())
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
System.out.println("准备完毕...请发出数据,88表示完毕");
while(true)
{
String str = wt.readLine();
out.println(str);
out.flush();
if(str.equals("88"))
{
break;
}
System.out.println("服务器端信息->"+in.readLine());
}
server.close();
wt.close();
out.close();
in.close();
}
catch(Exception err)
{
err.printStackTrace();
}
}
public static void main(String args[])
{
new ClientSP().sending();
}
}
[/php]
2 DatabaseServer.java
[php]
import java.io.*;
import java.net.*;
import java.sql.*;
public class DatabaseServer
{
Connection con = null;
ResultSet rs = null;
private void reading()
{
try
{
System.out.println("服务器初始化...");
ServerSocket server = new ServerSocket(8383);
Socket client = server.accept();
System.out.println("服务器准备完毕...");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while(true)
{
String str = in.readLine();
System.out.println("客户信息->"+str);
System.out.println("正在查询数据库,请稍候...");
String returnClent = query(str);
out.print(returnClent);
out.flush();
System.out.println("发送成功");
if(str.equals("88"))
{
out.print("88");
out.flush();
break;
}
}
out.close();
in.close();
server.close();
client.close();
}
catch(Exception err)
{
err.printStackTrace();
}
}
private String query(String str)
{
String username = null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbcdbc:test");
PreparedStatement pstmt = con.prepareStatement("SELECT username FROM test WHERE userid=?");
pstmt.setString(1,str);
rs = pstmt.executeQuery();
if(rs.next())
{
username = rs.getString("username");
}
else
{
username = "查无此人!";
}
}
catch(Exception err)
{
err.printStackTrace();
}
finally
{
if(rs != null)
{
try
{
rs.close();
}
catch(Exception err)
{
err.printStackTrace();
}
}
if(con != null)
{
try
{
con.close();
}
catch(Exception err)
{
err.printStackTrace();
}
}
}
return username;
}
public static void main(String args[])
{
new DatabaseServer().reading();
}
}
[/php] |
|