我正在尝试制作一个简单的服务器客户端程序,该程序允许我将滑块值从IOS客户端发送到java服务器。我现在被卡住了,因为我收到的数据我不知道如何处理。我正在寻求一点指导。我将提供到目前为止我所拥有的客户端和服务器端代码。我想了解更多关于插座的信息,并感谢我能得到的任何帮助。现在我只想能够从IOS发送一个字符串,并用java将其打印到控制台。我只想从测试字符串开始。我的最终目标是将浮动值转换为字符串,然后返回到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();
}
}
}