繁体   English   中英

JAVA Chat Sever使用TCP协议与Iphone客户端通信

[英]JAVA Chat Sever communicates with Iphone clients using TCP protocol

我想开发处理TCP协议的JAVA聊天服务器的演示。

客户将使用I电话。

如何在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Ò

向我建议一些解决此问题的好方法。

我已经用以下代码解决了这个问题:

    //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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM