简体   繁体   English

通过套接字发送字符串。 服务器未收到

[英]Sending a String through socket. Server not receiving it

I've been struggling lately to find a way to deliver strings through a socket file. 我最近一直在努力寻找一种通过套接字文件传递字符串的方法。 I'm planning to create a remote tool(client) to execute things based on the received message(server). 我打算创建一个远程工具(客户端),以根据收到的消息(服务器)执行操作。 I've searched answers for my problem on google and i found some things and managed to understand things but I also got some problems (i'm new to programming, not yet in college). 我在google上搜索了我的问题的答案,发现了一些东西并设法理解了一些东西,但是我也遇到了一些问题(我是编程的新手,还没上大学)。

I would appreciate any help in this matter 我将不胜感激

SocketService.java ---- class file = serverside SocketService.java ----类文件=服务器端

 package socket;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

public class ServiceSocket {
    static ServerSocket myService;
    static Socket thesocket;
    static Thread socketThread;
    public static boolean socketRunning;
     public static DataInputStream socketMessage;


    public static void initialise(String localhost, int portNumber ){
        // make a server socket//////
        try {
            myService = new ServerSocket(portNumber);
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //////////////////////////////

    }

    public static void deploySocket(){
        socketThread = new Thread() {
            public void run(){

                // making connection
                System.out.println("VVaiting for connection...");
                try {
                    thesocket = myService.accept();
                    System.out.println("Connection made");
                    socketRunning = true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ////////////////////////////////////
                try {
                    StartBrain();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                if(socketRunning = false) {
                try {
                    thesocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
      }

    };
        socketThread.start();
  }

     public static String getSocketMessage() throws IOException {

         try {
            socketMessage = new DataInputStream(thesocket.getInputStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
         boolean looprunning = true;
         String message = null;
         System.out.println("entering loop");
               do {
                   try {
                   while (socketMessage.readUTF() != null) {

                message = socketMessage.readUTF();
                looprunning = false;
                      }
                   } catch (EOFException e) {

                   }
               }while(looprunning);

                System.out.println("Message received from UTF: " + message);
                System.out.println("loop exited vvith message");   

         if(message == null) {
          message = "no message";
         }

         return message;
     }

     public static void StartBrain() throws IOException {
         System.out.println("socket brain started");
        String BrainMessage = getSocketMessage();
             if(BrainMessage == "command") {
                 System.out.println("Command EXECUTED HAHA");
             } else if(BrainMessage == "taskschedule") {
                 System.out.println("task scheduled");
             } else {
                 System.out.println("no command received");
             }

         }

Main.java ----- class file = serverside package main; Main.java -----类文件=服务器端程序包main;

import socket.ServiceSocket;

public class Main {

   public static void main(String[] args) {

      ServiceSocket.initialise("localhost", 3535);
      ServiceSocket.deploySocket();
    }
   }  
} 

Main.java = CLIENT Main.java =客户

package mainPackage;

import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;

public class Main {
    private static Socket clientSocket;

    public static void sendMessage(String message) throws IOException, InterruptedException {
        DataOutputStream dOut = new DataOutputStream(Main.clientSocket.getOutputStream());

        dOut.writeUTF(message);
        dOut.flush(); 

        dOut.close();
            }

    public static void main(String[] args) throws Exception {
     //   String modifiedSentence;

        clientSocket = new Socket("localhost", 3535);
        System.out.println("Initializing");
        sendMessage("command");

        boolean running = true;
     while(running) {
         TimeUnit.SECONDS.sleep(3);
         sendMessage("taskschedule");
     }
     clientSocket.close();

    }
}

main problem 主要问题

 do {
                   try {
                   while (socketMessage.readUTF() != null) {

                message = socketMessage.readUTF();
                looprunning = false;
                      }
                   } catch (EOFException e) {

                   }
               }while(looprunning);

it doesn't read the string/UTF 它不读取字符串/ UTF

It does read it, here: 它确实在这里读取它:

while (socketMessage.readUTF() != null) {

and then throws it away as you're not assigning the return-value to a variable, and then tries to read another one, here: 然后在不将返回值分配给变量的情况下将其丢弃,然后尝试在此处读取另一个值:

message = socketMessage.readUTF();

but the one (first) message you send is already gone. 但是您发送的(第一条)消息已经消失了。

You have problem in 你有问题

while (socketMessage.readUTF() != null) {
    message = socketMessage.readUTF();
    looprunning = false;
}

First call to method readUTF() will block thread and read UTF string from socket, but you discard this value and try read string second time. 首次调用方法readUTF()将阻塞线程并从套接字读取UTF字符串,但是您将放弃此值并尝试第二次读取字符串。

If you replace socketMessage.readUTF() != null with looprunning server will log this messages: 如果使用looprunning服务器替换socketMessage.readUTF() != nulllooprunning服务器将记录以下消息:

VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
no command received

PS Command is not recognized because use compare objects (string is object) with == , but you must use equals . 无法识别PS命令,因为将比较对象(字符串是对象)与== ,但是必须使用equals

public static void StartBrain() throws IOException {
    System.out.println("socket brain started");
    String BrainMessage = getSocketMessage();
    if (BrainMessage.equals("command")) {
        System.out.println("Command EXECUTED HAHA");
    } else if (BrainMessage.equals("taskschedule")) {
        System.out.println("task scheduled");
    } else {
        System.out.println("no command received");
    }

}

Server log: 服务器日志:

VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
Command EXECUTED HAHA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM