0
2 웨이 채팅 메시징 시스템을 만들려고합니다. 메시지를 보내고 상대방이 메시지를 보내고 메시지를 다시 보내고 상대방도 응답 할 수 있습니다. 내 코드를 만들 때 사용할 수있는 코드를 찾았지만 정상적으로 작동하지만 단방향 메시지 시스템 일 뿐이므로 클라이언트가 서버와 클라이언트에 메시지를 보낼 수있는 코드를 원했습니다. 지금이 클라이언트 인 편도2 웨이 메시징 시스템 (C#에서 소켓 사용)
서버
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace Sever
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(4523);
serverSocket.Start();
Console.WriteLine("Started!");
while (true)
{
TcpClient clientSocket = serverSocket.AcceptTcpClient();
handleClient clientx = new handleClient();
clientx.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
Thread xthread = new Thread(msg);
ctThread.Start();
}
private void Chat()
{
byte[] buffer = new byte[100];
while (true)
{
NetworkStream ns = clientSocket.GetStream();
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
}
}
private void msg()
{
byte[] buf2 = new byte[100];
while (true)
{
TcpClient client = new TcpClient("localhost", 4523);
NetworkStream ns = client.GetStream();
string str = Console.ReadLine();
BinaryWriter bw = new BinaryWriter(client.GetStream());
bw.Write(str);
}
}
}
}
입니다 그래도
내 코드는 다음과 같습니다.
class Program
{
static void Main(string[] args)
{
while (true)
{
TcpClient client = new TcpClient("localhost",4523);
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[100];
string str = Console.ReadLine();
BinaryWriter bw = new BinaryWriter(client.GetStream());
bw.Write(str);
}
}
}
실종 상태의 클라이언트는 무엇입니까?
프로그램에 두 개의 스레드/작업이 필요합니다. 계속해서 채팅 메시지가 수신되는 경우, 다른 하나는 사용자 입력을 요청하고 채팅 메시지를 보냅니다. 발신자와 수신자 스레드. 'System.Threading.Tasks'를보십시오 –
요청에 따라 메시지를 보내는 동안 다른 스레드에서 메시지를 수신 할 수 있습니다. 스트림을 사용하여 종료 한 후에 스트림을'Close()'및'Dispose()'하는 것을 기억하십시오. –
@ m.rogalski는 ** 서버 **에서 같은 Binary Writer를 사용하려고 생각하고있었습니다. 그런 식으로 작동합니까 ?? – Thomas