客户端
- String line=null;
- line=bufr.readLine();
- out.write(line);
- out.newLine();
- s.shutdownOutput();
复制代码
服务端
- String name;
- name=in.readLine();
复制代码 写入输出流之后,new了一行,,,服务端readLine应该可以的呀????
模拟客户端登陆问题,,,全部代码如下
客户端
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.Socket;
- class UserLogin {
- public static void main(String[] args) {
- Socket s=null;
- BufferedReader bufr=null;
- try {
- s=new Socket("192.168.8.100",10008);
- bufr=new BufferedReader(new InputStreamReader(System.in));
- BufferedWriter out=
- new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- BufferedReader in=
- new BufferedReader(new InputStreamReader(s.getInputStream()));
- String line=null;
- line=bufr.readLine();
- out.write(line);
- out.newLine();
- s.shutdownOutput();
- line=in.readLine();
- System.out.println(line);
- } catch (Exception e) {
- // TODO: handle exception
- }finally{
- if (s!=null) {
- try {
- s.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (bufr!=null) {
- try {
- bufr.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码
服务端
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- class LoginServer {
- public static void main(String[] args) throws IOException {
- ServerSocket ss=new ServerSocket(10008);
- while (true) {
- Socket s=ss.accept();
- new Thread(new ServerLogin(s)).start();
- }
- }
- }
- class ServerLogin implements Runnable{
- private Socket s;
- boolean flag=false;
- ServerLogin(Socket s){
- this.s=s;
- }
- public void run(){
- File file=new File("D:\\myclass\\6.txt");
- BufferedReader bufr=null;
- try {
- String ip=new String(s.getInetAddress().getHostAddress());
- System.out.println(ip+":"+"正在尝试登录");
- bufr=new BufferedReader(new FileReader(file));
- BufferedWriter out=
- new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
- BufferedReader in=
- new BufferedReader(new InputStreamReader(s.getInputStream()));
- String line=null;
- String name;
- name=in.readLine();
- while ((line=bufr.readLine())!=null) {
- if (line.equals(name)) {
- flag=true;
- break;
- }
- }
- if (flag) {
- System.out.println(name+"登陆成功");
- out.write(ip+":"+name+"登录成功");
- }else{
- System.out.println(name+"登录失败");
- out.write("用户名错误");
- out.newLine();
- }
- s.shutdownOutput();
- } catch (Exception e) {
- e.toString();
- throw new RuntimeException("客户登录失败");
- }finally{
- if (bufr!=null) {
- try {
- bufr.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码
|