2011-11-28 68 views
0

我在Java中套接字服務器,現在我需要簡單的TCP套接字在我的iOS應用程序,將:的iOS簡單套接字通信

  • 開放套接字連接
  • 能夠發送和收到的消息
  • 關閉連接

所以,只有基本的東西......我需要最簡單的解決方案。

我發現很少的解決方案,但似乎沒有爲我工作。如果你能指引我正確的方向,我將非常感激。我需要帶有說明的代碼。

謝謝!

+0

當你說你已經嘗試過,你看過哪些解決方案?我想我們寧願不重複你可能已經看到的任何事情。 – Luke

+0

幾乎所有的前20個結果,你在google上得到谷歌,當你鍵入iPhone套接字...我只是問,如果任何人有工作的例子是可以理解的... – iblagajic

+0

我假設你嘗試[本教程](http:// www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server)那麼,對吧?它有什麼「不適用於你」? – dasblinkenlight

回答

0
package jcolibri.examples.ABXRecommender; 

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.net.ServerSocket; 
import java.net.Socket; 

public class FileServer { 
public static void main (String [] args) throws IOException { 
    // create socket 
    @SuppressWarnings("resource") 
    ServerSocket servsock = new ServerSocket(13267); 
    while (true) { 

     String str = "temp.png"; 
      File myFile = new File(str); 
      String absolutePathOfFirstFile = myFile.getAbsolutePath(); 
      FileInputStream fis = new FileInputStream(absolutePathOfFirstFile); 

     //File myFile = new File ("temp.png"); 
     //FileInputStream fis = new FileInputStream(myFile); 

     System.out.println("Waiting..."); 
     Socket sock = servsock.accept(); 
     System.out.println("Accepted connection : " + sock); 

     // sendfile 

     byte [] mybytearray = new byte [(int)myFile.length()]; 

     @SuppressWarnings("resource") 
    BufferedInputStream bis = new BufferedInputStream(fis); 
     bis.read(mybytearray,0,mybytearray.length); 
     OutputStream os = sock.getOutputStream(); 
     System.out.println("Sending..."); 
     os.write(mybytearray,0,mybytearray.length); 
     os.flush(); 
     sock.close(); 
     } 
    } 
} 

此代碼從某處輕微改編。不記得它在哪裏,它適用於我。你的iOS代碼應該知道你的電腦的IP地址。

希望有所幫助。