public class TcpClientLogin {
// 这是用户登录客户端
static Socket socket = null;
static OutputStream outputStream = null;
static InputStream inputStream = null;
static Scanner scanner = null;
public static void main(String[] args) {
try {
while (true) {
// 获取socket对象 传递IP地址和端口号
socket = new Socket("127.0.0.1", 8080);
scanner = new Scanner(System.in);
// 获取字节输出流给服务端发送数据
outputStream = socket.getOutputStream();
// 获取字节输入流响应数据给客户端
inputStream = socket.getInputStream();
System.out.println("请输入用户名称。。。");
String user = scanner.next();
System.out.println("请输入用户密码。。。");
String pwd = scanner.next();
// userName=mayikt&userPwd=123456
String text = "user=" + user + "&" + "pwd=" + pwd;
// 写入数据
outputStream.write(text.getBytes());
// 响应数据
byte[] bytes = new byte[1024];
// 获取读取到的长度
int length = inputStream.read(bytes);
// 转换字符串 是Java lan包下的
String result = new String(bytes, 0, length);
if ("成功".equals(result)) {
System.out.println("登录成功。。。");
} else {
System.out.println("登录失败。。。");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭资源
socket.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|