我同时运行服务器应用程序和客户端应用程序,但客户端无法向服务器发送消息
本文关键字:应用程序 服务器 客户端 消息 运行 | 更新日期: 2023-09-27 18:31:30
我是套接字编程的新手,现在我想有一个聊天应用程序,客户端是我的 PC 中的模拟器,服务器现在也是我 PC 上的 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代码(作为Clinet):包 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;
}
}
}
你必须使用 ip 10.0.2.2