2013-07-23 88 views
1

我想做一个简单的服务器客户端程序,它允许我将滑动条值从IOS客户端发送到java服务器。我现在被卡住了,因为我收到了我不知道如何处理的数据。我正在寻找一点指导。我将提供迄今为止我所拥有的客户端和服务器端代码。我想了解更多关于套接字,并感谢我能得到任何帮助。现在我只想从IOS发送一个字符串并将其打印到java中的控制台。我只想从一个测试字符串开始。我的最终目标是通过将float值转换为字符串然后返回到java端来将滑块的值发送给服务器。ios滑块数据到java服务器使用TCP套接字

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); 
     } 
    } 


} 

据我所知,连接的处理方式是非常草率和欣赏任何建议。 我可以打通到Java方面的一些数据来当我移动IOS上的滑块,它看起来像这样在控制台:

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 = [email protected] 
waiting for socket accept 
socket accepted and returns: Socket[addr=/127.0.0.1,port=61578,localport=7896] 
inputStream = [email protected] 

这是[email protected],我不知道如何处理。

回答

0

试试我的代码,它适用于我。

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(); 
     } 
    } 
} 
相关问题