SerialPort.ReadLine Método
Definição
public:
System::String ^ ReadLine();
public string ReadLine ();
member this.ReadLine : unit -> string
Public Function ReadLine () As String
Retornos
O conteúdo do buffer de entrada até a primeira ocorrência de um valor NewLine.The contents of the input buffer up to the first occurrence of a NewLine value.
Exceções
A porta especificada não está aberta.The specified port is not open.
A operação não foi concluída antes do encerramento do tempo limite.The operation did not complete before the time-out period ended.
- ou --or-
Nenhum byte foi lido.No bytes were read.
Exemplos
O exemplo de código a seguir demonstra o uso da SerialPort classe para permitir que dois usuários conversem de dois computadores separados conectados por um cabo de modem nulo.The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate computers connected by a null modem cable. Este exemplo de código é parte de um exemplo de código maior fornecido para a SerialPort classe.This code example is part of a larger code example provided for the SerialPort class.
public:
static void Main()
{
String^ name;
String^ message;
StringComparer^ stringComparer = StringComparer::OrdinalIgnoreCase;
Thread^ readThread = gcnew Thread(gcnew ThreadStart(PortChat::Read));
// Create a new SerialPort object with default settings.
_serialPort = gcnew SerialPort();
// Allow the user to set the appropriate properties.
_serialPort->PortName = SetPortName(_serialPort->PortName);
_serialPort->BaudRate = SetPortBaudRate(_serialPort->BaudRate);
_serialPort->Parity = SetPortParity(_serialPort->Parity);
_serialPort->DataBits = SetPortDataBits(_serialPort->DataBits);
_serialPort->StopBits = SetPortStopBits(_serialPort->StopBits);
_serialPort->Handshake = SetPortHandshake(_serialPort->Handshake);
// Set the read/write timeouts
_serialPort->ReadTimeout = 500;
_serialPort->WriteTimeout = 500;
_serialPort->Open();
_continue = true;
readThread->Start();
Console::Write("Name: ");
name = Console::ReadLine();
Console::WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console::ReadLine();
if (stringComparer->Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort->WriteLine(
String::Format("<{0}>: {1}", name, message) );
}
}
readThread->Join();
_serialPort->Close();
}
static void Read()
{
while (_continue)
{
try
{
String^ message = _serialPort->ReadLine();
Console::WriteLine(message);
}
catch (TimeoutException ^) { }
}
}
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
Public Shared Sub Main()
Dim name As String
Dim message As String
Dim stringComparer__1 As StringComparer = StringComparer.OrdinalIgnoreCase
Dim readThread As New Thread(AddressOf Read)
' Create a new SerialPort object with default settings.
_serialPort = New SerialPort()
' Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName)
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate)
_serialPort.Parity = SetPortParity(_serialPort.Parity)
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits)
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits)
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake)
' Set the read/write timeouts
_serialPort.ReadTimeout = 500
_serialPort.WriteTimeout = 500
_serialPort.Open()
_continue = True
readThread.Start()
Console.Write("Name: ")
name = Console.ReadLine()
Console.WriteLine("Type QUIT to exit")
While _continue
message = Console.ReadLine()
If stringComparer__1.Equals("quit", message) Then
_continue = False
Else
_serialPort.WriteLine([String].Format("<{0}>: {1}", name, message))
End If
End While
readThread.Join()
_serialPort.Close()
End Sub
Public Shared Sub Read()
While _continue
Try
Dim message As String = _serialPort.ReadLine()
Console.WriteLine(message)
Catch generatedExceptionName As TimeoutException
End Try
End While
End Sub
Comentários
Observe que embora esse método não retorne o NewLine valor, o NewLine valor é removido do buffer de entrada.Note that while this method does not return the NewLine value, the NewLine value is removed from the input buffer.
Por padrão, o ReadLine método será bloqueado até que uma linha seja recebida.By default, the ReadLine method will block until a line is received. Se esse comportamento for indesejável, defina a ReadTimeout propriedade com qualquer valor diferente de zero para forçar o ReadLine método a gerar um TimeoutException se uma linha não estiver disponível na porta.If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.
Se for necessário alternar entre o texto de leitura e a leitura de dados binários do fluxo, selecione um protocolo que defina cuidadosamente o limite entre o texto e os dados binários, como a leitura manual de bytes e a decodificação dos dados.If it is necessary to switch between reading text and reading binary data from the stream, select a protocol that carefully defines the boundary between text and binary data, such as manually reading bytes and decoding the data.
Observação
Como a SerialPort classe armazena em buffer os dados e o fluxo contido na BaseStream propriedade não, os dois podem entrar em conflito com a quantidade de bytes disponíveis para leitura.Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two might conflict about how many bytes are available to read. A BytesToRead propriedade pode indicar que há bytes a serem lidos, mas esses bytes podem não estar acessíveis para o fluxo contido na BaseStream propriedade porque eles foram armazenados em buffer para a SerialPort classe.The BytesToRead property can indicate that there are bytes to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have been buffered to the SerialPort class.