我想开发处理 TCP 协议的 JAVA 聊天服务器的演示。
客户将是 I-phone。
如何在 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Ò
建议我一些很好的方法来解决这个问题。