2012-10-19 126 views
0

我想開發處理TCP協議的JAVA聊天服務器演示程序。JAVA聊天服務器使用TCP協議與Iphone客戶端通信

客戶將是我的電話。

如何在JAVA聊天服務器和Objective C之間進行通信?

我試圖

public class ChatServer { 
     ServerSocket providerSocket; 
     Socket connection = null; 
     ObjectOutputStream out; 
     ObjectInputStream in; 
     String message; 

     ChatServer() throws IOException { 

     } 

     void run() { 
      try { 
       // 1. creating a server socket 
       providerSocket = new ServerSocket(2001, 10); 
       // 2. Wait for connection 
       System.out.println("Waiting for connection"); 
       connection = providerSocket.accept(); 
       System.out.println("Connection received from " 
         + connection.getInetAddress().getHostName()); 
       // 3. get Input and Output streams 
       out = new ObjectOutputStream(connection.getOutputStream()); 
       out.flush(); 
       // in = new ObjectInputStream(connection.getInputStream()); 
       sendMessage("Connection successful"); 
       BufferedReader in1 = new BufferedReader(new InputStreamReader(
         connection.getInputStream())); 

       // out = new PrintWriter(socket.getOutputStream(),true); 
       int ch; 
    //   String line=""; 
    //   do{ 
    //    ch=in1.read(); 
    //    line+=(char)ch; 
    //    
    //   }while(ch!=-1); 
       String line = in1.readLine(); 


       System.out.println("you input is :" + line); 
       // 4. The two parts communicate via the input and output streams 
       /* 
       * do { try { message = (String) in.readObject(); 
       * System.out.println("client>" + message); if 
       * (message.equals("bye")) sendMessage("bye"); } catch 
       * (ClassNotFoundException classnot) { 
       * System.err.println("Data received in unknown format"); } } while 
       * (!message.equals("bye")); 
       */ 
      } catch (IOException ioException) { 
       ioException.printStackTrace(); 
      } finally { 
       // 4: Closing connection 
       try { 
        // in.close(); 
        out.close(); 
        providerSocket.close(); 
       } catch (IOException ioException) { 
        ioException.printStackTrace(); 
       } 
      } 
     } 

     void sendMessage(String msg) { 
      try { 
       out.writeObject(msg); 
       out.flush(); 
       System.out.println("server>" + msg); 
      } catch (IOException ioException) { 
       ioException.printStackTrace(); 
      } 
     } 

     /** 
     * @param args 
     * @throws IOException 
     */ 
     public static void main(String[] args) throws IOException { 
      // TODO Auto-generated method stub 
      ChatServer server = new ChatServer(); 
      while (true) { 
       server.run(); 
      } 
     } 

    } 

和目標C我已經使用

LXSocket *socket; 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    socket = [[LXSocket alloc]init]; 

    if ([socket connect:@"127.0.0.1" port:2001]) { 
     NSLog(@"socket has been created"); 
    } 
    else { 
     NSLog(@"socket couldn't be created created"); 
    } 

    @try { 
     [self sendData]; 

    }@catch (NSException * e) { 
     NSLog(@"Unable to send data"); 
    } 

    [super viewDidLoad]; 
} 
-(IBAction)sendData{ 
    // [socket sendString:@"M\n"]; 
    [socket sendObject:@"Masfds\n"]; 
} 

我能夠通信,但我得到與消息所附一些不必要的比特,將其從目標C發送。

輸出在服務器端: 從連接1接收 收到U $nullÒ

建議我一些很好的辦法來解決這個問題。

回答

0

我已經解決了這個問題,此代碼:

//Server 

     package com.pkg; 

     import java.io.BufferedReader; 
     import java.io.IOException; 
     import java.io.InputStream; 
     import java.io.InputStreamReader; 
     import java.io.PrintStream; 
     import java.io.Reader; 
     import java.io.UnsupportedEncodingException; 
     import java.net.ServerSocket; 
     import java.net.Socket; 

     public class ChatServer { 

      public static void main(String args[]) { 
       int port = 6789; 
       ChatServer server = new ChatServer(port); 
       server.startServer(); 
      } 

      // declare a server socket and a client socket for the server; 
      // declare the number of connections 

      ServerSocket echoServer = null; 
      Socket clientSocket = null; 
      int numConnections = 0; 
      int port; 

      public ChatServer(int port) { 
       this.port = port; 
      } 

      public void stopServer() { 
       System.out.println("Server cleaning up."); 
       System.exit(0); 
      } 

      public void startServer() { 
       // Try to open a server socket on the given port 
       // Note that we can't choose a port less than 1024 if we are not 
       // privileged users (root) 

       try { 
        echoServer = new ServerSocket(port); 
       } catch (IOException e) { 
        System.out.println(e); 
       } 

       System.out.println("Server is started and is waiting for connections."); 
       System.out 
         .println("With multi-threading, multiple connections are allowed."); 
       System.out.println("Any client can send -1 to stop the server."); 

       // Whenever a connection is received, start a new thread to process the 
       // connection 
       // and wait for the next connection. 

       while (true) { 
        try { 
         clientSocket = echoServer.accept(); 
         numConnections++; 
         Server2Connection oneconnection = new Server2Connection(
           clientSocket, numConnections, this); 
         new Thread(oneconnection).start(); 
        } catch (IOException e) { 
         System.out.println(e); 
        } 
       } 
      } 
     } 

     class Server2Connection implements Runnable { 
      BufferedReader is; 
      PrintStream os; 
      Socket clientSocket; 
      int id; 
      ChatServer server; 
      InputStream isr; 
      private static final int BUFFER_SIZE = 512; // multiples of this are 
                 // sensible 

      public Server2Connection(Socket clientSocket, int id, ChatServer server) { 
       this.clientSocket = clientSocket; 
       this.id = id; 
       this.server = server; 
       System.out.println("Connection " + id + " established with: " 
         + clientSocket); 
       try { 
        isr = clientSocket.getInputStream(); 
        is = new BufferedReader(new InputStreamReader(
          clientSocket.getInputStream())); 
        os = new PrintStream(clientSocket.getOutputStream()); 
       } catch (IOException e) { 
        System.out.println(e); 
       } 
      } 

      public void run() { 
       String line; 
       try { 
        boolean serverStop = false; 

        while (true) { 
         line = is.readLine(); 
         if (line != null) { 
          System.out.println("Received " + line + " from Connection " 
            + id + "."); 
          os.println("Hello this is server:" + line); 
          if (line.equalsIgnoreCase("stop")) { 
           serverStop = true; 
           break; 

          } 

         } else { 
          break; 
         } 

         // int n = Integer.parseInt(line); 
         // if (n == -1) { 
         // serverStop = true; 
         // break; 
         // } 
         // if (n == 0) 
         // break; 
         // os.println("" + n * n); 

        } 

        System.out.println("Connection " + id + " closed."); 
        is.close(); 
        os.close(); 
        clientSocket.close(); 

        if (serverStop) 
         server.stopServer(); 
       } catch (IOException e) { 
        System.out.println(e); 
       } 
      } 

     } 


    //client 

    package com.pkg; 

    import java.io.*; 
    import java.net.*; 

    public class Requester { 
     public static void main(String[] args) { 

     String hostname = "localhost"; 
     int port = 6789; 

     // declaration section: 
     // clientSocket: our client socket 
     // os: output stream 
     // is: input stream 

      Socket clientSocket = null; 
      DataOutputStream os = null; 
      BufferedReader is = null; 

     // Initialization section: 
     // Try to open a socket on the given port 
     // Try to open input and output streams 

      try { 
       clientSocket = new Socket(hostname, port); 
       os = new DataOutputStream(clientSocket.getOutputStream()); 
       is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
      } catch (UnknownHostException e) { 
       System.err.println("Don't know about host: " + hostname); 
      } catch (IOException e) { 
       System.err.println("Couldn't get I/O for the connection to: " + hostname); 
      } 

     // If everything has been initialized then we want to write some data 
     // to the socket we have opened a connection to on the given port 

     if (clientSocket == null || os == null || is == null) { 
      System.err.println("Something is wrong. One variable is null."); 
      return; 
     } 

     try { 
      while (true) { 
      System.out.print("Enter an integer (0 to stop connection, -1 to stop server): "); 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      String keyboardInput = br.readLine(); 
      os.writeBytes(keyboardInput + "\n"); 

    //  int n = Integer.parseInt(keyboardInput); 
    //  if (n == 0 || n == -1) { 
    //   break; 
    //  } 
      if(keyboardInput.equalsIgnoreCase("stop")){ 
       break; 
      } 
      String responseLine = is.readLine(); 
      System.out.println("Server returns its square as: " + responseLine); 
      } 

      // clean up: 
      // close the output stream 
      // close the input stream 
      // close the socket 

      os.close(); 
      is.close(); 
      clientSocket.close(); 
     } catch (UnknownHostException e) { 
      System.err.println("Trying to connect to unknown host: " + e); 
     } catch (IOException e) { 
      System.err.println("IOException: " + e); 
     } 
     }   
    } 

//objective c client 
// 
// RKViewController.m 
// ConnectServer 
// 
// Created by Yogita Kakadiya on 10/27/12. 
// Copyright (c) 2012 __MyCompanyName__. All rights reserved. 
// 

#import "RKViewController.h" 

@interface RKViewController() 

@end 

@implementation RKViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; 

    NSError *err = nil; 
    if ([socket connectToHost:@"192.168.2.3" onPort:6789 error:&err]) 
    { 
     NSLog(@"Connection performed!"); 
     [socket readDataWithTimeout:-1 tag:0]; 
    } 
    else 
    { 
     NSLog(@"Unable to connect: %@", err); 
    } 

} 


- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port 
{ 
    NSLog(@"Socket:DidConnectToHost: %@ Port: %hu", host, port); 

    connected = YES; 

    if(connected) 
    { 
     NSData *message = [[NSData alloc] initWithBytes:"Ranjit\n" length:8]; 
     [sock writeData:message withTimeout:-1 tag:0]; 
    } 
} 

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err 
{ 
    NSLog(@"SocketDidDisconnect:WithError: %@", err); 
    connected = NO; 
    //We will try to reconnect 
    //[self checkConnection]; 
} 

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag 
{ 
    //[self processReceivedData:data]; 

    NSString *readMessage = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding]; 
    NSLog(@"RECIEVED TEXT : %@",readMessage); 

    [sock readDataWithTimeout:-1 tag:0]; 
    //NSData *message = data; 

} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 

@end 
+0

朋友們,請讓我知道該怎麼做客戶端到客戶端通信與此相同的代碼。中間件將是JAVA服務器。 –

+0

嘿,你有沒有實現聊天功能?我想做同樣的事你能幫助我嗎? –

+0

請你幫幫我嗎? –