I encountered this situation, the server does not receive information about the client, the client does not receive the information returned by the server
However, the client and server side socket connection is created, and this problem is where do
Novice, please enlighten. . .
Client (ios) code
/ /
/ / TestUdpClientAppDelegate.m
/ / TestUdpClient
/ /
/ / Created by Xie Wei on 11-6-5.
/ / Copyright 2011 年 e-linkway.com. All rights reserved.
/ /
# Import "TestTcpClientAppDelegate.h"
# Import "AsyncUdpSocket.h"
# Import "AsyncSocket.h"
# Define SERVER_IP @ "192.168.1.109"
/ / # Define SERVER_IP @ "127.0.0.1"
# Define SERVER_PORT 3005
@ Implementation TestUdpClientAppDelegate
@ Synthesize window = _window;
@ Synthesize sendSocket = _sendSocket;
/ / Send Message
- (IBAction) sendString
{
NSData * data = [NSData dataWithBytes: "This is a test \ n" length: 15];
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);
} Else {
NSLog (@ "connect succ");
}
[_sendSocket SetRunLoopModes: [NSArray arrayWithObject: NSRunLoopCommonModes]];
}
if (connectOK)
{
[_sendSocket WriteData: data withTimeout: -1 tag: 0];
}
}
- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions
{
float button_center_y = 20;
float button_center_offset = 50;
_sendButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
_sendButton.frame = CGRectMake (0, 0, 200, 30);
_sendButton.center = CGPointMake (320/2, button_center_y + = button_center_offset);
[_sendButton AddTarget: self action: @ selector (sendString) forControlEvents: UIControlEventTouchUpInside];
[_sendButton SetTitle: @ "Send String" forState: UIControlStateNormal];
[Self.window addSubview: _sendButton];
[Self.window makeKeyAndVisible];
return YES;
}
# Pragma mark - tcp
- (Void) onSocket: (AsyncSocket *) sock didConnectToHost: (NSString *) host port: (UInt16) port
{
NSLog (@ "% 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];
}
/ / Here must use streaming data
- (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) onSocketDidDisconnect: (AsyncSocket *) sock
{
NSLog (@ "% s% d", __ FUNCTION__, __ LINE__);
self.sendSocket = nil;
}
# Pragma mark -
- (Void) dealloc
{
[_window Release];
[Super dealloc];
}
@ End
Server side (java) code
package com.dvn.li.main;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.log4j.Logger;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import com.dvn.li.handler.Demo1ServerHandler;
public class MinaServer01 {
private static Logger logger = Logger.getLogger (MinaServer01.class);
private static int PORT = 3005;
public static void main (String [] args) {
IoAcceptor acceptor = null;
try {
/ / Create a non-blocking server side Socket
acceptor = new NioSocketAcceptor ();
/ / Set filters (using the supplied text newline Mina codec)
acceptor.getFilterChain (). addLast (
"Codec",
new ProtocolCodecFilter (new TextLineCodecFactory (Charset
. ForName ("UTF-8"), LineDelimiter.WINDOWS.getValue (),
LineDelimiter.WINDOWS.getValue ())));
/ / Set the read data buffer size
acceptor.getSessionConfig (). setReadBufferSize (2048);
/ / Write channel 10 seconds without operation enters an idle state
acceptor.getSessionConfig (). setIdleTime (IdleStatus.BOTH_IDLE, 10);
/ / Bind logical processors
acceptor.setHandler (new Demo1ServerHandler ());
/ / Bind port
acceptor.bind (new InetSocketAddress (PORT));
logger.info ("server started successfully ... port number is:" + PORT);
} Catch (Exception e) {
logger.error ("server initiates exception ....", e);
e.printStackTrace ();
}
}
}
package com.dvn.li.handler;
import java.util.Date;
import org.apache.log4j.Logger;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
public class Demo1ServerHandler extends IoHandlerAdapter {
public static Logger logger = Logger.getLogger (Demo1ServerHandler.class);
@ Override
public void sessionCreated (IoSession session) throws Exception {
logger.info ("server 111 and the client to create a connection ...");
/ / System.out.println ("server 111 and the client to create a connection ...");
}
@ Override
public void sessionOpened (IoSession session) throws Exception {
logger.info ("server 111 and the client connection open ...");
/ / System.out.println ("server 111 and the client connection open ...");
}
@ Override
public void messageReceived (IoSession session, Object message)
throws Exception {
System.out.println ("messageReceived");
String msg = message.toString ();
System.out.println ("server 111 receives the data as:" + msg);
logger.info ("the server 111 receives the data as:" + msg);
if ("bye". equals (msg)) {/ / server disconnected condition
session.close ();
}
Date date = new Date ();
session.write ("1234567");
/ / Thread.sleep (10000);
}
@ Override
public void messageSent (IoSession session, Object message) throws Exception {
session.close ();
logger.info ("server 111 Send message successfully ...");
/ / System.out.println ("server 111 Send message successfully ...");
}
@ Override
public void sessionClosed (IoSession session) throws Exception {
}
@ Override
public void sessionIdle (IoSession session, IdleStatus status)
throws Exception {
logger.info ("service end 111 enters an idle state ...");
/ / System.out.println ("service end 111 enters an idle state ...");
}
@ Override
public void exceptionCaught (IoSession session, Throwable cause)
throws Exception {
logger.error ("server 111 sends an exception ...", cause);
/ / System.out.println ("server 111 sends an exception ...");
}
}
Reply:
I always use bsd socket write, this never used, ah, Bangniding top
Reply:
Does anybody know?
Reply:
Oh thank you ah
Reply:
Is not, and network byte order for it? I search the web for this, but do not understand, help. . .
Java socket communication problems with iOS socket
Communication between them will be problems, because the java vm's i / o operations are big-endian byte order, and ios, linux, windows these platforms bsd socket is little-endian byte order.
There are two solutions:
1. The java side manually changed little-endian
Online open source java code: http://www.downloadroute.com/ledatastream-by-canadian-mind-products/downloader.html
(2) the client is manually changed to big-endian
In iOS platform as an example here,
int big = NSSwapHostIntToBig (little);
In this record, I hope to help a friend experiencing the same problem.
Reply:
I use the GCD AsyncSocket.
Connect server side SOCKET communication is no problem.
You are using RunLoop written.
Some places I did not look.
Reply:
I realized later use c socket connections, and the windows of the java server communication is no problem, but still not thoroughly understand why AsyncSocket not do it. .
Ask the next, gcd gcd of AsyncSocket and did not have what difference does it?
Reply:
LZ can capture first look to see whether the packet is sent out, and if it was received packet
Reply:
For testing the communication is normal, you can start regardless of the byte order, this does not affect the data packets to accept it or not, only affects the data analysis; IOS aspects: 1. You see whether the port is receiving data binding is successful, 2 sets whether the agency correct (visual you this is no problem)
Reply:
connectOK = [_sendSocket connectToHost: SERVER_IP onPort: SERVER_PORT error: & error];
You will not be repeated phrase (> = 2) Click the button to bind to port failure cause?
Reply:
Not fail
Reply:
In this demo http://download.csdn.net/detail/qqqwww198273/5372045, there is a need comrades removed
Reply:
Is to deal with multiple threads are not the same.
GCD is a new multi-threading it.
Reply:
Fifth floor, buddy, I also use the GCD AsyncSocket achieve communication, successful connection, but the data is transmitted, the server can not receive data. Clients use the [_sendSocket writeData: data withTimeout: -1 tag: 0] In this way, the server is used to write the stream mode. Want to know how to change the client should send data before it can be achieved? Looking forward to your reply.
No comments:
Post a Comment