本文整理汇总了C#中TcpListener.AcceptSocket方法的典型用法代码示例。如果您正苦于以下问题:C# TcpListener.AcceptSocket方法的具体用法?C# TcpListener.AcceptSocket怎么用?C# TcpListener.AcceptSocket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TcpListener
的用法示例。
在下文中一共展示了TcpListener.AcceptSocket方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetUp
} // end method DisplayMessage
// accepts connections from 2 players
public void SetUp()
{
DisplayMessage("Waiting for players...\r\n");
// set up Socket
listener =
new TcpListener(IPAddress.Parse("127.0.0.1"), 50000);
listener.Start();
// accept first player and start a player thread
players[0] = new Player(listener.AcceptSocket(), this, 0);
playerThreads[0] =
new Thread(new ThreadStart(players[0].Run));
playerThreads[0].Start();
// accept second player and start another player thread
players[1] = new Player(listener.AcceptSocket(), this, 1);
playerThreads[1] =
new Thread(new ThreadStart(players[1].Run));
playerThreads[1].Start();
// let the first player know that the other player has connected
lock (players[0])
{
players[0].threadSuspended = false;
Monitor.Pulse(players[0]);
} // end lock
} // end method SetUp
示例2: Main
static void Main(string[] args)
{
DateTime now = DateTime.Now;
Console.WriteLine("[" + now.ToString("tthh:mm:ss") + "]");
TcpListener listener = null;
bool Start_Service = false;
try
{
//IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
//IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPAddress ipAddress = IPAddress.Any;
listener = new TcpListener(ipAddress, 3000);
listener.Start();
Console.WriteLine("** ChatServer **");
Console.WriteLine("1. 대기중입니다.");
while (!Start_Service)
{
Socket socket = listener.AcceptSocket();
Console.WriteLine("[+접속클라이언트]:" + socket.RemoteEndPoint);
if (socket.Connected)
{
//ChatSupporter 스레드 생성
ChatSupporter cs = new ChatSupporter(socket);
//ChatSupporter room에 저장
room.AddChatSupporter(cs);
}
}
}
catch
{
Console.WriteLine("서버 생성 도중 에러");
return;
}
}
示例3: Main
public static void Main()
{
TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client connected");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader =
new System.IO.StreamReader(networkStream);
string theString = "Sending";
streamWriter.WriteLine(theString);
Console.WriteLine(theString);
streamWriter.Flush();
theString = streamReader.ReadLine();
Console.WriteLine(theString);
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Close();
Console.WriteLine("Exiting...");
}
示例4: Main
static void Main(string[] args)
{
String n="", horariosOut="";
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener tcpListener = new TcpListener(ip, 5050);
tcpListener.Start();
Socket serverSock = tcpListener.AcceptSocket();
if (serverSock.Connected)
{
NetworkStream con = new NetworkStream(serverSock);
//Archivo local en servidor, el cual se activará para mandar un correo
StreamWriter crearArchivoLocal = new StreamWriter("C:/Users/Dell/Documents/datoAdjunto.txt");
StreamWriter enviarDatos = new StreamWriter(con);
StreamReader recibirDatos = new StreamReader(con);
if(recibirDatos.ReadLine()!=""){
horariosOut = "Horarios disponibles: 1) 9:00 am 2) 12:00 pm 3) 3:00pm 4) 5:00 pm 5) 12:00 am. Seleccione alguna opción indicando con un numero";
enviarDatos.WriteLine(horariosOut);
enviarDatos.Flush();
}
if(recibirDatos.ReadLine().Equals("2")){
n = (recibirDatos.ReadLine() );
crearArchivoLocal.WriteLine(n);
}
if(recibirDatos.ReadLine().Equals("3")){
EnviarEmail enviarCorreo = new EnviarEmail();
bool exito = enviarCorreo.EnviarMail(recibirDatos.ReadLine(), "Datos de reservación", n, "AerolinasMisael", "[email protected]", "josueupbc");
if (exito == true)
{
enviarDatos.WriteLine(n + " El correo fue enviado exitosamente");
Console.WriteLine("El correo ha sido enviado exitosamente");
}
else
Console.Error.WriteLine("No fue posible enviar el correo");
enviarDatos.Flush();
}
recibirDatos.Close();
crearArchivoLocal.Close();
enviarDatos.Close();
con.Close();
serverSock.Close();
}
else
Console.WriteLine("Fallo en la conexion");
Console.ReadKey();
}
示例5: Listen
private NetworkStream serverStream; //Stream - incoming
#endregion Fields
#region Methods
//listening to the server
public void Listen()
{
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(m_IPAdress);
bool errorOcurred = false;
Socket connection = null; //The socket that is listened to
try
{
//Creating listening Socket
this.listener = new TcpListener(remoteIPAddress, inPort);
//Starts listening
this.listener.Start();
Debug.Log("listening...");
//Establish connection upon client request
while (!navigator.gameInstance.GameFinished)
{
//connection is connected socket
connection = listener.AcceptSocket();
if (connection.Connected)
{
//To read from socket create NetworkStream object associated with socket
this.serverStream = new NetworkStream(connection);
List<Byte> inputStr = new List<byte>();
int asw = 0;
while (asw != -1)
{
asw = this.serverStream.ReadByte();
inputStr.Add((Byte)asw);
}
reply = Encoding.UTF8.GetString(inputStr.ToArray());
this.serverStream.Close();
ThreadPool.QueueUserWorkItem(new WaitCallback(navigator.gameInstance.Resolve), (object)reply); //parse the message from the
}
}
}
catch (Exception e)
{
Debug.Log("RECEIVING Failed! \n " + e.Message);
errorOcurred = true;
}
finally
{
if (connection != null)
if (connection.Connected)
connection.Close();
if (errorOcurred)
Debug.Log("Error occured while listening! \n ");
//this.Listen();
}
}
示例6: ts
void ts()
{
try {
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local address
TcpListener listener=new TcpListener(ipAd,801);
listener.Start(); // Listen for connections
Debug.Log("The local End point is: " + listener.LocalEndpoint );
Debug.Log("Waiting for a connection.....");
System.Diagnostics.Process process= new System.Diagnostics.Process();
process.StartInfo.FileName = flashCamPath;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
process.Start(); // Start the air webcam app
Socket s = listener.AcceptSocket(); // Accept incomming connection
Debug.Log("Connection accepted from "+s.RemoteEndPoint);
byte[] b=new byte[sizeof(int)];
s.Receive(b); // Receive what we expect to be an integer
Console.WriteLine("Recieved...");
camWidth = BitConverter.ToInt32(b, 0); // Set the width of the image
Debug.Log("Image width: " + camWidth);
s.Receive(b); // Receive what we expect to be another integer
camHeight = BitConverter.ToInt32(b, 0); // Set the height
Debug.Log("Image height: " + camHeight);
c = new Color[camWidth*camHeight]; // Create a new Color object
byte[] img=new byte[camWidth * camHeight * RGBA]; // Create a byte array
Debug.Log("Ready to receive webcam stream");
while (receiveData) { // loop around this until we kill the thread
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("ready")); // Tell the client we are ready
s.Receive(img); // Receive the pixel buffer
// Convert the pixel buffer into the color object. I'm too lazy to explain this in detail.
for (int i = 0; i < camHeight; ++i) {
for (int j = 0; j < camWidth * RGBA; j += RGBA) {
c[(i*camWidth) + (j/RGBA)].a = img[(i*camWidth*RGBA) + j] / 255f;
c[(i*camWidth) + (j/RGBA)].r = img[(i*camWidth*RGBA) + j +1] / 255f;
c[(i*camWidth) + (j/RGBA)].g = img[(i*camWidth*RGBA) + j + 2] / 255f;
c[(i*camWidth) + (j/RGBA)].b = img[(i*camWidth*RGBA) + j + 3] / 255f;
}
}
Thread.Sleep(100); // Make sure the thread has a short nap
}
s.Close(); // When we exeit the loop, close the connection
listener.Stop(); // Stop listeneing
process.Kill(); // Kill the flash app
} catch (Exception e) {
Debug.Log("Error..... " + e.StackTrace);
}
}
示例7: Main
public static void Main()
{
try
{
bool status = true ;
string servermessage = "" ;
string clientmessage = "" ;
TcpListener tcpListener = new TcpListener(8100) ;
tcpListener.Start() ;
Console.WriteLine("Server Started") ;
Socket socketForClient = tcpListener.AcceptSocket() ;
Console.WriteLine("Client Connected") ;
NetworkStream networkStream = new NetworkStream(socketForClient) ;
StreamWriter streamwriter = new StreamWriter(networkStream) ;
StreamReader streamreader = new StreamReader(networkStream) ;
while(status)
{
if(socketForClient.Connected)
{
servermessage = streamreader.ReadLine() ;
Console.WriteLine("Client:"+servermessage) ;
if((servermessage== "bye" ))
{
status = false ;
streamreader.Close() ;
networkStream.Close() ;
streamwriter.Close() ;
return ;
}
Console.Write("Server:") ;
clientmessage = Console.ReadLine() ;
streamwriter.WriteLine(clientmessage) ;
streamwriter.Flush() ;
}
}
streamreader.Close() ;
networkStream.Close() ;
streamwriter.Close() ;
socketForClient.Close() ;
Console.WriteLine("Exiting") ;
}
catch(Exception e)
{
Console.WriteLine(e.ToString()) ;
}
}
示例8: Run
private void Run()
{
_log.info("ConsorsGate::Run", "starting TCP listener on port 65000.");
TcpListener tcpl=new TcpListener(65000);
tcpl.Start();
while(!_quit){
Socket socket=tcpl.AcceptSocket();
if(socket.Connected){
_log.info("ConsorsGate::Run", "new socket connected.");
ConsorsGateHandler cgh=new ConsorsGateHandler(_log, socket);
_sm.add(cgh);
}
}
_log.info("ConsorsGate::Run", "Leaving now.");
}
示例9: Update
void Update()
{
tcpListener = new TcpListener(5555);
tcpListener.Start();
serverSocket = tcpListener.AcceptSocket();
try
{
if (serverSocket.Connected)
{
Debug.Log("Connect");
while (true)
{
networkStream = new NetworkStream(serverSocket);
streamWriter = new StreamWriter(networkStream);
streamReader = new StreamReader(networkStream);
//MemoryStream stream1 = new MemoryStream();
//DeSerealizaton();
//MyNameSpace.Player Player = new MyNameSpace.Player {X = GameObject.Find("Player").transform.position.x,Y = GameObject.Find("Player").transform.position.y, Z = GameObject.Find("Player").transform.position.z};
//MyNameSpace.SomeContainer someContainer = new MyNameSpace.SomeContainer {Player = Player};
//MyNameSpace.SomeContainer desSomeObject = JsonConvert.DeserializeObject<MyNameSpace.SomeContainer>(jsonString);
jsonString = streamReader.ReadLine();
Debug.Log(jsonString);
MyNameSpace.Player Player = new MyNameSpace.Player {X = GameObject.Find("Player").transform.position.x,Y = GameObject.Find("Player").transform.position.y, Z = GameObject.Find("Player").transform.position.z};
MyNameSpace.SomeContainer someContainer = new MyNameSpace.SomeContainer {Player = Player};
MyNameSpace.SomeContainer desSomeObject = JsonConvert.DeserializeObject<MyNameSpace.SomeContainer>(jsonString);
//stream1.Position = 0;
x = desSomeObject.Player.X;
y = desSomeObject.Player.Y;
z = desSomeObject.Player.Z;
GameObject.Find("Player").transform.position = new Vector3(x,y,z);
}
}
if (serverSocket.Connected)
{
serverSocket.Close();
}
}
catch (SocketException ex)
{
Debug.Log(ex);
}
}
示例10: acceptconnection
public static void acceptconnection(out TcpListener Listener, out Socket client_socket)
{
// Use any IP
IPAddress ipAdd = IPAddress.Any;
//Start listening
Listener = new TcpListener(ipAdd, 8001);
//Wait for connection
Listener.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
Listener.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
client_socket = Listener.AcceptSocket();
Console.WriteLine("Connection accepted from " + client_socket.RemoteEndPoint);
}
示例11: startDispatching
public void startDispatching(TcpListener listener, ILogger logger,
IProtocolFactory protoFactory)
{
// Run forever, accepting and spawning threads to service each connection
for (;;) {
try {
listener.Start();
Socket clntSock = listener.AcceptSocket(); // Block waiting for connection
IProtocol protocol = protoFactory.createProtocol(clntSock, logger);
Thread thread = new Thread(new ThreadStart(protocol.handleclient));
thread.Start();
logger.writeEntry("Created and started Thread = " + thread.GetHashCode());
} catch (System.IO.IOException e) {
logger.writeEntry("Exception = " + e.Message);
}
}
/* NOT REACHED */
}
示例12: RunServerImpl
public void RunServerImpl()
{
//yield return null;
TcpListener tcpListener = null;
try
{
//ip주소를 나타내는 객체 생성. TcpListener생성시 인자로 사용
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
//TcpListener class를 이용하여 클라이언트 연결 받아 들임
tcpListener = new TcpListener(ipAd, TestServer.PORT);
tcpListener.Start();
//Console.WriteLine("멀티스레드 Test 창 :Waiting for connections...");
Debug.Log("S: Waiting for connections.. \n");
while (true)
{
//accepting the connection
Socket client = tcpListener.AcceptSocket();
Debug.Log(string.Format("S: Accepted socket {0} \n", client.Connected));
ClientHandler cHandler = new ClientHandler();
//passing calue to the thread class
cHandler.clientSocket = client;
//creating a new thread for the client
Thread clientThread = new Thread(new ThreadStart(cHandler.runClient));
clientThread.Start();
}
}
catch (Exception exp)
{
//Console.WriteLine("Exception :" + exp);
Debug.Log("S: Exception :" + exp);
}
finally
{
tcpListener.Stop();
}
}
示例13: acceptconnection
public static void acceptconnection(out TcpListener myList, out Socket s)
{
IPAddress ipAd = IPAddress.Parse("161.115.86.57");
//use local m/c IP address, and
//use the same in the client
/* Initializes the Listener */
myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
}
示例14: Main
public static void Main()
{
try
{
IPAddress ipAd = IPAddress.Parse("10.2.20.29");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
示例15: Main
public static void Main()
{
try
{
IPAddress ipAd=IPAddress.Parse("127.0.0.1");
TcpListener myList=new TcpListener(ipAd,8001);
myList.Start();
Console.WriteLine("��8001�˿��������...");
Console.WriteLine("���ؽڵ�Ϊ��"+myList.LocalEndpoint);
Console.WriteLine("�ȴ�����...");
Socket s=myList.AcceptSocket();
Console.WriteLine("�������� "+s.RemoteEndPoint);
byte[] b=new byte[100];
int k=s.Receive(b);
Console.WriteLine("�ѽ���...");
for(int i=0;i<k;i++)
{
Console.Write(Convert.ToChar(b[i]));
}
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\n �ѷ��ͻ�Ӧ��Ϣ");
s.Close();
myList.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
Console.ReadKey();
}