send image or video to a server using socket streaming
I successfully open a socket to send data to it.When i tried to send an image it crashed and when i send string to it it works fine.I am converting an image to data and then put this data into the string that has to be send to server.
Need guidance, please help
Below is the code , i am using to connect with stream.
NSString *urlStr = @"http://182.71.22.107:1935/VideoCalling/5d14a9bc-b816-4c82-bbb7-623d18243a02.sdp/playlist.m3u8";
if (![urlStr isEqualToString:@""])
{
NSURL *website = [NSURL URLWithString:urlStr];
if (!website)
{
NSLog(@"%@ is not a valid URL");
return;
}
NSHost *host = [NSHost hostWithName:[website host]];
// iStream and oStream are instance variables
[NSStream getStreamsToHost:host port:8081 inputStream:&iStream outputStream:&oStream];
[iStream retain];
[oStream retain];
[iStream setDelegate:self];
[oStream setDelegate:self];
NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:@"abc.png"], 90);
// Convert from host to network endianness
uint32_t length = (uint32_t)htonl([data length]);
// Don't forget to check the return value of 'write'
[oStream write:(uint8_t *)&length maxLength:4];
[oStream write:[data bytes] maxLength:length];//writes to stream
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
}
Here i write to stream
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
int byteIndex;
switch(eventCode) {
case NSStreamEventHasSpaceAvailable:{
if (stream == oStream) {
//NSString * str = [NSString stringWithFormat:@"sdsdfdfggghhfhfh"];
NSString * str = [[NSString alloc]initWithData:datap encoding:NSUTF16StringEncoding];
NSLog(@"%@,lenght===%d",str,[str length]);
const uint8_t * rawstring = (const uint8_t *)[str UTF8String];
[oStream wr开发者_运维知识库ite:rawstring maxLength:strlen(15)];
[oStream close];
}
UIAlertView *a = [[UIAlertView alloc]initWithTitle:@"h" message:@"Available" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[a show];
[a release];
}
break;
Try this sample by apple developer in PostController
精彩评论