5
回答
iOS socket怎么和java通讯啊
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

本人新手,在网上下载了ios的socket通信的列子。我用java做服务器 。但是服务器读不出来数据


客户端:

//
//  clientTest.m
//  clientTest
//
//  Created by apple on 12-4-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "clientTest.h"

#define WELCOME_MSG  0
#define ECHO_MSG     1
#define WARNING_MSG  2

#define READ_TIMEOUT 15.0
#define READ_TIMEOUT_EXTENSION 10.0

#define SERVER_IP   @"192.168.1.104"
#define SERVER_PORT 9527 

@implementation clientTest

@synthesize sendSocket = _sendSocket;


- (id)init
{
	if(self = [super init])
	{
        NSString * inputMsgStr = @"你好";
        NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"]; //stringByAppendingString:str是在一个字符串后面追加一个字符串str
        NSData *data = [content dataUsingEncoding: NSUTF8StringEncoding];//数据使用编码类型
        
        NSLog(@"data:%@",[data description]);
        static BOOL connectOK = NO;//判断连接是否成功
        
        if (!_sendSocket)
        {
            self.sendSocket = [[[AsyncSocket alloc] initWithDelegate: self] autorelease];
            
            NSError *error;
            connectOK = [_sendSocket connectToHost:SERVER_IP onPort: SERVER_PORT error: &error];
            
            if (!connectOK)
            {
                NSLog(@"connect error: %@", error);
            }
            
            [_sendSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
        }
        
        if (connectOK) 
        {
            NSLog(@"---------------%@",[data description]);
            [_sendSocket writeData: data withTimeout: -1 tag: 0];
            
        }
 
	}
	return self;
}

-(void)connect
{
//
//    NSData *data = [@"12345678" dataUsingEncoding: NSUTF8StringEncoding]; 
//    
//    static BOOL connectOK = NO;
//    
//    if (!_sendSocket)
//    {
//        self.sendSocket = [[[AsyncSocket alloc] initWithDelegate: self] autorelease];
//        
//        NSError *error;
//        connectOK = [_sendSocket connectToHost: SERVER_IP onPort: SERVER_PORT error: &error];
//        
//        if (!connectOK)
//        {
//            NSLog(@"connect error: %@", error);
//        }
//        
//        [_sendSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
//    }
//    
//    if (connectOK) 
//    {
//        [_sendSocket writeData: data withTimeout: -1 tag: 0];
//    }
//    
//    [NSThread detachNewThreadSelector:@selector(newThread) toTarget:self withObject:nil];
}

-(void)newThread{
    
    NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];
    
 
    
    
    [p release];
}

#pragma mark - tcp


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
	NSLog(@"hh%s %d", __FUNCTION__, __LINE__);
    
    [_sendSocket readDataWithTimeout: -1 tag: 0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"%s %d, tag = %ld", __FUNCTION__, __LINE__, tag);
    
    [_sendSocket readDataWithTimeout: -1 tag: 0];
}

// 这里必须要使用流式数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *msg = [[[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding] autorelease];
    
    NSLog(@"%s %d, msg = %@", __FUNCTION__, __LINE__, msg);
    
    [_sendSocket readDataWithTimeout: -1 tag: 0];
}

//- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
//{
//    NSLog(@"%s %d, err = %@", __FUNCTION__, __LINE__, err);
//}
//
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"%s %d", __FUNCTION__, __LINE__);
    
    self.sendSocket = nil;
}

@end
服务端:
package com.chg;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MySocket {

	private ServerSocket ss = null;
	private PrintWriter pw = null;
	BufferedReader br = null;
	InputStream is;
	
	public void start(){
		try {
			ss = new ServerSocket(9527);
			while(true){
				System.out.println("我在9527端口监听");
				Socket s = ss.accept();
//				br = new BufferedReader(new InputStreamReader(s.getInputStream()));
				System.out.println("----------------------");
//				String str = br.readLine();
//				System.out.println("str="+str);
				is = s.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int len;
				byte[] b = new byte[1024];
				while((len = is.read(b))!=-1){
					System.out.println("len = "+len);
					baos.write(b, 0, len);
				}
				byte[] data = baos.toByteArray();
				pw = new PrintWriter(s.getOutputStream(),true);
				pw.println("我是服务器,我收到了你发来的消息");
				System.out.println("客户端发来的消息:"+new String(data));
				System.err.println("--------------------------------------------------------------------------------------------------");
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

iOS
举报
尐帥鱼
发帖于5年前 5回/3K+阅
顶部