yvk5384 2021-10-03 22:32 采纳率: 100%
浏览 133
已结题

客户端通过服务器进行通信

是tcp字符流通信,但不知道哪儿出问题了,想要大老修改一下代码
这是客户端的

package Task1;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author 15122
 */
public class Client {
    public String HOST_NAME;
    public int HOST_PORT;
    
    public Client(String Name,int Port){
        HOST_NAME=Name;
        HOST_PORT=Port;
    }
    
    
    public void startClient(){
      Socket socket = null;
      Scanner keyboardInput = new Scanner(System.in);
      try
      {  socket = new Socket("127.0.0.1", HOST_PORT);
         System.err.println("Connection successful " );
      }
      catch (IOException e)
      {  System.err.println("Client could not make connection: " + e);
         System.exit(-1);
      }
      BufferedReader br;
      BufferedWriter bw;
      InputStreamReader isr;
      OutputStream os;
      InputStream is;
      do{
      try
      {  
         os = socket.getOutputStream();
         bw = new BufferedWriter(new OutputStreamWriter(os));
         bw.write(HOST_NAME+" : "+keyboardInput.nextLine());
         bw.newLine();
         bw.flush();
         
        
         is = socket.getInputStream();
         isr = new InputStreamReader(is);
         br = new BufferedReader(isr);
         String info = null;
         info = br.readLine();
         if (info != null) {
            System.out.println(info);
            } if(info==null){            
             is.close();
             os.close();
             bw.close();
             br.close();
             System.out.println("done");
            }
      }
       catch (UnknownHostException e) {
            e.printStackTrace();
       }
      catch (IOException e)
      {  System.err.println("Client error with chat: " + e);
      }
    }while(!"Exit".equals(keyboardInput.nextLine()));
        try {
            socket.close();
             System.out.println("done1");
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 
}

这是服务器的

package Task1;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
 *
 * @author 15122
 */
public class Server {
    
    public static final int PORT = 8888;
    
    
    public Server(){
    
    }
    
    public void startServer(){
    
    ServerSocket serverSocket = null;
    try
    {
        serverSocket = new ServerSocket(PORT);
        System.out.println("Server started at "+ InetAddress.getLocalHost() + " on port " + PORT);
    }
    catch(IOException e){
         System.err.println("Server can't listen on port: " + e);
         System.exit(-1);
    }
    try{
        while(true)
        {
            Socket socket = serverSocket.accept();
            ServerThread serverThread = new ServerThread(socket);
            serverThread.start();
            InetAddress address = socket.getInetAddress();
            System.out.println("Connection made with "+ address);
        }
    }
    catch(IOException e){
        System.err.println("Can't accept client connection: " + e);
    }
    System.out.println("Server finishing");
    }

    

这是服务器线程

package Task1;

/**
 *
 * @author 15122
 */
import java.io.*;
import java.net.Socket;
 

public class ServerThread extends Thread {
    Socket socket = null;
 
    public ServerThread(Socket socket) {
        this.socket = socket;
    }
 
    public void run() {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream os = null;
        PrintWriter pw = null;
        String info;
        info = "start";
        try {
            is = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            info = br.readLine();
            do{ 
                System.out.println( info);
                bw.write(info);
                bw.newLine();
                bw.flush();
                info =br.readLine();
           
            }while(br.readLine()!=null);
            }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        do{
         try {
                    if (pw != null)
                        pw.close();
                    if (os != null)
                        os.close();
                    if (is != null)
                        is.close();
                    if (isr != null)
                        isr.close();
                    if (br != null)
                        br.close();
                    if (socket != null)
                        socket.close();
                     System.out.println("done2");
                } catch (IOException e) {
                    e.printStackTrace();
 
                }
        }while(info == null);
    }
}


这是客户端1


package Task1;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author 15122
 */
public class TestChat {
    public static void main(String[] args) {
        Client client1 = new Client("Client1",8888);
        client1.startClient();
    }
}

这是客户端2


```java

package Task1;

/**
 *
 * @author 15122
 */
public class TestChat1 {
    public static void main(String[] args) {
        
        Client client2 = new Client("Client2",8888);
       
        client2.startClient();
    }
}

这是服务器启动main()

```java
package Task1;

/**
 *
 * @author 15122
 */
public class runServer {
     public static void main(String[] args) {
         Server server = new Server();
         server.startServer();
     }
}

这些代码有部分是从网上找来的

  • 写回答

6条回答 默认 最新

  • 程序员小牧之 Java领域新星创作者 2021-10-05 23:59
    关注

    只需更改Client和ServerThread的代码即可,参考:

    package TCP;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedWriter;
    import java.io.OutputStreamWriter;
    import java.io.OutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.Scanner;
    /**
     *
     * @author 15122
     */
    public class Client {
        public String HOST_NAME;
        public int HOST_PORT;
    
        public Client(String Name,int Port){
            HOST_NAME=Name;
            HOST_PORT=Port;
        }
        public void startClient(){
            Socket socket = null;
            Scanner keyboardInput = new Scanner(System.in);
            try {
                socket = new Socket("127.0.0.1", HOST_PORT);
                System.err.println("Connection successful " );
            }
            catch (IOException e) {
                System.err.println("Client could not make connection: " + e);
                System.exit(-1);
            }
            BufferedReader br = null;
            BufferedWriter bw=null;
            InputStreamReader isr=null;
            OutputStream os = null;
            InputStream is = null;
            try {
                os = socket.getOutputStream();
                bw = new BufferedWriter(new OutputStreamWriter(os));
                is = socket.getInputStream();
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
    
                while (true){
                    String toServer=keyboardInput.nextLine();
                    bw.write(HOST_NAME+" : "+toServer);
                    bw.newLine();
                    bw.flush();
                    String info = null;
                    info = br.readLine();
                    if (info != null) {
                        System.out.println(info);
                    }
                    if(info==null){
                        is.close();
                        os.close();
                        bw.close();
                        br.close();
                        System.out.println("done");
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
    package TCP;
    
    /**
     *
     * @author 15122
     */
    import java.io.*;
    import java.net.Socket;
    
    
    public class ServerThread extends Thread {
        Socket socket = null;
    
        public ServerThread(Socket socket) {
            this.socket = socket;
        }
    
        public void run() {
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            OutputStream outputStream = null;
            PrintWriter printWriter = null;
            BufferedWriter bufferedWriter = null;
            String info;
            try {
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
    
                while (true) {
                    info = bufferedReader.readLine();
                    if(info!=null){
                        System.out.println(info);
                        bufferedWriter.write(info);
                        bufferedWriter.newLine();
                        bufferedWriter.flush();
                    }else{
                        try {
                            if (printWriter != null)
                                printWriter.close();
                            if (outputStream != null)
                                outputStream.close();
                            if (inputStream != null)
                                inputStream.close();
                            if (inputStreamReader != null)
                                inputStreamReader.close();
                            if (bufferedReader != null)
                                bufferedReader.close();
                            if (socket != null)
                                socket.close();
                            System.out.println("done2");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
    
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    }
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 10月14日
  • 已采纳回答 10月6日
  • 创建了问题 10月3日

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化