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Ò
建議我一些很好的辦法來解決這個問題。
朋友們,請讓我知道該怎麼做客戶端到客戶端通信與此相同的代碼。中間件將是JAVA服務器。 –
嘿,你有沒有實現聊天功能?我想做同樣的事你能幫助我嗎? –
請你幫幫我嗎? –