Good morning. I have a question, and I ask you the following questions.
I am doing network programming in Java under Mac environment and in C ++ under Windows environment.
The code looks like this:
Java(Mac) Tcp Server
import java.net.*;
import java.io.*;
import.java.util.Date;
import.java.text.SimpleDateFormat;
public class TcpServer
{
ServerSocket serverSocket = null;
public static void Main(String args[])
{
try
{
serverSocket = new ServerSocket(12345);
System.out.println(getTime() + "Ready");
}
catch(IOException e)
{
e.printStackTrace();
}
while(true)
{
try
{
System.out.println(getTime() + "Wait");
Socket client = serverSocket.accept();
System.out.println(getTime() + "Connect");
OutputStream out = client.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
// send to client
dos.writeUTF("[Notice] Test Message1 from Server");
System.out.println(getTime() + "Write");
dos.close();
client.close();
}
catch(IOException e)
{
e.printStackStrace();
}
}
}
static String getTime()
{
SimpleDateFormat f = new SimpleDateFormat("[hh:mm:ss]");
return f.format(new Date());
}
}
and C++(Windows) Tcp Client:
int main()
{
WSAData wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN servAddr{};
servAddr.sin_family = AF_INET;
inet_pton(AF_INET, "192.168.1.23", &servAddr.sin_addr.s_addr);
servAddr.sin_port = htons(12345);
connect(sock, (SOCKADDR*)&servAddr, sizeof SOCKADDR_IN);
char buffer[256];
// receive a message like "\0\[Notice] Test Message1 from Server"
int length = recv(sock, buffer, 255, 0);
buffer[length] = '\0';
std::cout << buffer << std::endl;
closesocket(sock);
WSACleanup();
}
When sending messages from Java and checking messages in C ++, buffer [0] and buffer [1] always contain strange values, and the messages are not output properly.
The proper message is printed at the end of the message.
Why?