繁体   English   中英

使用TCP套接字将iOS滑块数据传输到Java服务器

[英]ios slider data to java server using tcp socket

我正在尝试制作一个简单的服务器客户端程序,该程序允许我将滑块值从IOS客户端发送到Java服务器。 我现在陷入困境,因为我收到的数据我不知道该如何处理。 我正在寻找一些指导。 我将提供到目前为止的客户端和服务器端代码。 我想了解有关套接字的更多信息,并感谢我可以获得的任何帮助。 现在,我只希望能够从IOS发送一个字符串并将其打印到Java中的控制台。 我只想从测试字符串开始。 我的最终目标是通过将float值转换为字符串,然后再返回Java端,将滑块的值发送到服务器。

iOS客户端代码

#import "ViewController.h"
@interface ViewController () <NSStreamDelegate>
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self TcpClientInitialise];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)SliderDidChange:(id)sender {

    UISlider *slider = (UISlider *)sender;
    float val = slider.value;

    self.SliderLabel.text = [NSString stringWithFormat:@"%f",val];
    [self TcpClientInitialise];
    NSString *response  = @"HELLO1234";
NSData *data = [[NSData alloc] initWithData:[response   dataUsingEncoding:NSUTF8StringEncoding]];

[OutputStream write:[data bytes] maxLength:[data length]];  //<<Returns actual number of bytes sent - check if trying to send a large number of bytes as they may well not have all gone in this write and will need sending once there is a hasspaceavailable event
    NSLog(@"Sent data on output stream");
    [InputStream close];
    [OutputStream close];



    }


- (void)TcpClientInitialise
{
NSLog(@"Tcp Client Initialise");

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;


    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", 7896, &readStream, &writeStream);

    InputStream = (__bridge NSInputStream *)readStream;
    OutputStream = (__bridge NSOutputStream *)writeStream;

[InputStream setDelegate:self];
[OutputStream setDelegate:self];

[InputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[OutputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[InputStream open];
[OutputStream open];
    }
    ...
    ...
    ...

和Java代码...

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Handler;

public class TCPServer {


private static PrintStream outputStream;

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    System.out.println("Main Test");
    ServerSocket statusServer = null;
    String number = null;
    DataInputStream inputStream = null;
    outputStream = null;
    Socket clientSocket = null;

 // Try to open a server socket on port 7896
    try {
        statusServer = new ServerSocket(7896);
        System.out.println("ServerSocket status server made");
     }
     catch (IOException e) {
        System.out.println(e);
        System.out.println("status server failed");
     }   

 // Create a socket object from the ServerSocket to listen and accept 
 // connections.
 // Open input and output streams

 try {
     while(true){       

            System.out.println("waiting for socket accept");
            clientSocket = statusServer.accept();
            System.out.print("socket accepted and returns: ");
            System.out.println(statusServer.accept());
            inputStream = new DataInputStream(clientSocket.getInputStream());
            number = inputStream.toString();
            System.out.print("inputStream = ");
            System.out.println(number);
            inputStream.close();
            clientSocket.close();

            //outputStream = new PrintStream(clientSocket.getOutputStream());
           }



         }   catch (IOException e) {
            System.out.println(e);
         }
     }


}

我了解连接的处理方式非常草率,非常感谢任何建议。 当我在IOS上移动滑块时,可以获得一些数据到达Java端,它在控制台中如下所示:

Main Test
ServerSocket status server made
waiting for socket accept
socket accepted and returns: Socket[addr=/127.0.0.1,port=61576,localport=7896]
inputStream = java.io.DataInputStream@2891fa78
waiting for socket accept
socket accepted and returns: Socket[addr=/127.0.0.1,port=61578,localport=7896]
inputStream = java.io.DataInputStream@5b8767ad

我不知道该如何处理的是java.io.DataInputStream@xxxxxxxx。

试试我的代码,它对我有用。

    NSInputStream *inputStream;
    NSOutputStream *outputStream;
    -(void) init{
        NSURL *website = [NSURL URLWithString:@"http://YOUR HOST"];

        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL,CFBridgingRetain([website host]),9876, &readStream, &writeStream);

        inputStream = (__bridge_transfer NSInputStream *)readStream;
        outputStream = (__bridge_transfer NSOutputStream *)writeStream;
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [outputStream open];
        [inputStream open];

        CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
        CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    }

- (void) sendMessage {

    // it is important to add "\n" to the end of the line
    NSString *response  = @"Say hello to Ukraine**\n**";
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];
    int sent = [outputStream write:[data bytes] maxLength:[data length]];
    NSLog(@"bytes sent: %d",sent);

    do{
        uint8_t buffer[1024];
        int bytes = [inputStream read:buffer maxLength:sizeof(buffer)];
        NSString *output = [[NSString alloc] initWithBytes:buffer length:bytes encoding:NSUTF8StringEncoding];
        NSLog(@"%@",output);
    } while ([inputStream hasBytesAvailable]);
}

Java服务器:

    public class ServerTest {
        public static void main(String[] args) {
            Thread thr = new Thread(new SocketThread());
            thr.start();
        }
    }

    class SocketThread implements Runnable {

        @Override
        public void run() {
            try {
                ServerSocket server = new ServerSocket(9876);
                while (true) {
                    new SocketConnection(server.accept()).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class SocketConnection extends Thread {
        InputStream input;
        PrintWriter output;
        Socket socket;

        public SocketConnection(Socket socket) {
            super("Thread 1");
            this.socket = socket;
            try {
                input = socket.getInputStream();
                output = new PrintWriter(new OutputStreamWriter(
                        socket.getOutputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                byte array[] = new byte[1024];
                while (true) {
                    do {
                        int readed = input.read(array);
                        System.out.println("readed == " + readed + " "
                                + new String(array).trim());
                        String sendString = new String(
                                "Hello Ukraine!".getBytes(),
                                Charset.forName("UTF-8"));
                        output.write(sendString);
                        output.flush();
                    } while (input.available() != 0);
                }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

暂无
暂无

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

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