(1) 建立服务端时,请选择左侧树形菜单中的 “TCP Server”,然后点击上方的“创建”按钮,会d出一个窗口,输入 TCP “监听端口”即可。
(2) 建立客户端时,请选择左侧树形菜单中的“TCP Client”,然后点击上方的“创建”按钮,在d出的对话框中,输入对方 IP,由于你在本地启动的服务端,所以 IP 输入 127001 即可,然后在“对方端口”中输入步骤 (1) 时设定的端口号,然后,点击上方的“连接”按钮,如此,客户端与服务端的 TCP 连接便已建立。
(3) 在左侧会 TCP Server 和 TCP Client 树形下会多出一个已建立的连接,点击它后,在右侧可以给对端发送消息。下面的代码示例创建 TcpListener。
using System;
using SystemIO;
using SystemNet;
using SystemNetSockets;
using SystemText;
class MyTcpListener
{
public static void Main()
{
TcpListener server=null;
try
{
// Set the TcpListener on port 13000
Int32 port = 13000;
IPAddress localAddr = IPAddressParse("127001");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests
serverStart();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop
while(true)
{
ConsoleWrite("Waiting for a connection ");
// Perform a blocking call to accept requests
// You could also user serverAcceptSocket() here
TcpClient client = serverAcceptTcpClient();
ConsoleWriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = clientGetStream();
int i;
// Loop to receive all the data sent by the client
while((i = streamRead(bytes, 0, bytesLength))!=0)
{
// Translate data bytes to a ASCII string
data = SystemTextEncodingASCIIGetString(bytes, 0, i);
ConsoleWriteLine("Received: {0}", data);
// Process the data sent by the client
data = dataToUpper();
byte[] msg = SystemTextEncodingASCIIGetBytes(data);
// Send back a response
streamWrite(msg, 0, msgLength);
ConsoleWriteLine("Sent: {0}", data);
}
// Shutdown and end connection
clientClose();
}
}
catch(SocketException e)
{
ConsoleWriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients
serverStop();
}
ConsoleWriteLine("\nHit enter to continue");
ConsoleRead();
}
}package test;
import javaioIOException;
import javautilDate;
import orgapachecommons>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)