2014-11-23 81 views
-2

我是新來的套接字編程,現在我想有一個聊天應用程序,客戶端是模擬器在我的電腦和服務器是現在我的電腦上的C#應用​​程序。我使用「127.0.0.1」爲客戶端設置了服務器IP。我同時運行服務器應用程序和客戶端應用程序,但客戶端無法向服務器發送消息。什麼是錯誤? 這是服務器側:我同時運行服務器應用程序和客戶端應用程序,但客戶端無法發送消息到服務器?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Net.Sockets; 

namespace serverConsol 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      TcpListener serverSocket = new TcpListener(8888); 
      int requestCount = 0; 
      TcpClient clientSocket = default(TcpClient); 
      serverSocket.Start(); 
      Console.WriteLine(" >> Server Started"); 
      clientSocket = serverSocket.AcceptTcpClient(); 
      Console.WriteLine(" >> Accept connection from client"); 
      requestCount = 0; 

      while ((true)) 
      { 
       try 
       { 
        requestCount = requestCount + 1; 
        NetworkStream networkStream = clientSocket.GetStream(); 
        byte[] bytesFrom = new byte[10025]; 
        networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize); 
        string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom); 
        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$")); 
        Console.WriteLine(" >> Data from client - " + dataFromClient); 
        string serverResponse = "Last Message from client" + dataFromClient; 
        Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse); 
        networkStream.Write(sendBytes, 0, sendBytes.Length); 
        networkStream.Flush(); 
        Console.WriteLine(" >> " + serverResponse); 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex.ToString()); 
       } 
      } 

      clientSocket.Close(); 
      serverSocket.Stop(); 
      Console.WriteLine(" >> exit"); 
      Console.ReadLine(); 
     } 
    } 
} 

而這就是Android代碼(如客戶爲例): 包com.app.client1;

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import android.os.Bundle; 
import android.app.Activity; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class MainActivity extends Activity 
{ 
    Thread ClientSocketTread; 
    String message="hi Server"; 
    public String ServeripFoConnect="127.0.0.1"; 
    public int Serverport=8888; 
    Socket requestSocket; 
    public PrintWriter out; 
    public TextView LbMsg; 
    public EditText InputMsg; 
    public Button BtnSend; 

    public Runnable MyClientsend = new Runnable() 
    { 
     public void run() 
     { 
     try 
      { 
      BufferedReader receiveRead; 
      InetAddress serverAddr = InetAddress.getByName(ServeripFoConnect);//TCPServer.SERVERIP   
      requestSocket = new Socket(serverAddr, Serverport); 
      while (true) 
      { 
       try 
       { 
        if (message != "") 
        { 
          out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream())),true); 
          out.println(message); 
          out.flush(); 
          message=""; 
          try 
          { 
           receiveRead = new BufferedReader(new InputStreamReader(requestSocket.getInputStream())); 
           if((receiveRead.read()) != -1) //receive from server 
           { 
            char[] buff = new char[(receiveRead.read()) +1]; 
            receiveRead.read(buff); 
            int i; 

            StringBuilder response= new StringBuilder(); 
            for(i=0;i<buff.length ;i++) 
            { 
             response.append(buff[i]); 
            } 

            String result = response.toString(); 
           } //end seccond if 

         } catch (Exception e) 
         { 
          // TODO: handle exception 
          Log.d("e111111111",e .toString()); 
          try 
          { 
           Log.d("e2222222222",e.toString()); 
          } 
          catch (Exception e2) 
          { 
           // TODO: handle exception 
           Log.d("e33333333333",e2 .toString()); 
          } 
         } 
        }//end first if 
        Thread.sleep(1000); 
       } 
       catch (Exception e) 
       { 
        // TODO: handle exception 
        Log.d("e44444444",e .toString()); 
        requestSocket.close(); 
       } 
      }//end while 

     } //end first try 
     catch (Exception e) 
     { 
      Log.d("e555555555",e .toString()); 
     } 
     finally 
     { 

     }//end finally 

    }//end run 
    };//end runnable 
    //EbdClient Socket 
    //-------------------------------------------------- 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //initial Object 
       LbMsg=(TextView) findViewById(R.id.LbMsg); 
       InputMsg=(EditText) findViewById(R.id.TbXInput); 
       BtnSend=(Button) findViewById(R.id.BtnSend);  
        try 
        { 
         ClientSocketTread = new Thread(MyClientsend); 
         ClientSocketTread.start(); 

        } catch (Exception e) 
        { 
         // TODO: handle exception 
         LbMsg.setText("ClientSocketTread not Start"); 
        } 
    } 
    //------------------------------------------ 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
    //------------------------------------------ 
    @Override 
    protected void onPause() 
    { 
     super.onPause(); 
     try 
     { 
      ClientSocketTread.stop(); 
     } 
     catch (Exception e) 
     { 
     } 
    } 
    //------------------------------------------ 
    ///Onclick Function 
public void Onclick(View v) 
{ 
    switch (v.getId()) 
     { 
      case R.id.BtnSend: 
      try 
      { 
       message=InputMsg.getText().toString(); 
      } 
      catch (Exception e) 
      { 
       LbMsg.setText("Erroe" + e); 
      } 
      break; 
     } 
    } 
} 
+0

只是谷歌 「在Android模擬器localhost」 的使用... – Selvin 2014-11-23 12:13:15

回答

相關問題