如何在java中实现TCP服务器和TCP客户端传输文件

前端之家收集整理的这篇文章主要介绍了如何在java中实现TCP服务器和TCP客户端传输文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我实现了简单的TCP服务器和TCP客户端类,可以从客户端发送消息到服务器,消息将在服务器端转换为大写,但是如何实现从服务器到客户端的传输文件,并从客户端上传文件到服务器.以下代码是我所得到的.

TCPClient.java

import java.io.*;
import java.net.*;

class TCPClient {
 public static void main(String args[]) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("127.0.0.1",6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + "\n");
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER:" + modifiedSentence);
        clientSocket.close();
    }
}

TCPServer.java:

import java.io.*;
import java.net.*;

class TCPServer {
    public static void main(String args[]) throws Exception {
        int firsttime = 1;
        while (true) {
            String clientSentence;
            String capitalizedSentence="";
            ServerSocket welcomeSocket = new ServerSocket(3248);
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            //System.out.println(clientSentence);
            if (clientSentence.equals("set")) {
                outToClient.writeBytes("connection is ");
                System.out.println("running here");
                //welcomeSocket.close();
                //outToClient.writeBytes(capitalizedSentence);
            }
            capitalizedSentence = clientSentence.toUpperCase() + "\n";
            //if(!clientSentence.equals("quit"))
            outToClient.writeBytes(capitalizedSentence+"enter the message or command: ");
            System.out.println("passed");
            //outToClient.writeBytes("enter the message or command: ");
            welcomeSocket.close();
            System.out.println("connection terminated");
        }
    }
}

所以,首先执行TCPServer.java,然后执行TCPClient.java,我尝试使用TCPServer.java中的if子句来测试用户的输入,现在我真的想要实现如何从双方(下载和上传).

解决方法

This链接应该有帮助.
原文链接:https://www.f2er.com/java/125698.html

猜你在找的Java相关文章