将 Java TCP 套接字聊天程序转换为 .net C# TCP 聊天程序

本文关键字:TCP 聊天 net 程序 程序转换 套接字 Java | 更新日期: 2023-09-27 17:48:54

我有一个Java TCP套接字聊天,我想转换为.net C#程序。代码如下...请帮忙。

import java.io.*;
import java.net.*;

class Connection
{
    public Socket s;
    public PrintWriter o;
    public BufferedReader i; 
}
class TCPChatServerThreadTask extends Thread
{
    Connection c;

public TCPChatServerThreadTask (ServerSocket serverSocket) throws IOException
{   
    c = new Connection ();
    c.s = serverSocket.accept ();
    c.o = new PrintWriter (c.s.getOutputStream (), true);
    c.i = new BufferedReader (new InputStreamReader (c.s.getInputStream ()));
    System.out.println (c.s.getInetAddress () + ":" + c.s.getPort () + " Connected");
    this.start ();
}   
public void run ()
{
    String fromClient = ">";
    try
    {               
        do
        {           
            fromClient = c.i.readLine ();
            System.out.println (c.s.getInetAddress () + ":" + c.s.getPort () + "> " + fromClient);
            for (int i = 0; i <  TCPChatServerThread.taskCount - 1; i ++)
            {
                TCPChatServerThread.task[i].c.o.println (c.s.getInetAddress () + ":" + c.s.getPort () + "> " + fromClient); 
            }
        }
        while (fromClient != "quit");
        System.out.println (c.s.getInetAddress () + ":" + c.s.getPort () + " Disconnected");
        c.o.close ();
        c.i.close ();       
        c.s.close ();
    }
    catch (IOException e)
    {
    } 
}
}
public class TCPChatServerThread
{
    ServerSocket serverSocket = null;
    static public String str = "?";
    static public TCPChatServerThreadTask[] task = new TCPChatServerThreadTask[10];
    static public int taskCount = 0;
public TCPChatServerThread () throws IOException
{       
    try
    {
        serverSocket = new ServerSocket (4455);
    }
    catch (IOException e)
    {
        System.err.println ("Server: Could not listen on port: ");
        System.exit (1);
    }
    System.out.println ("Server: Listening on port: ");
    while (true)
    {
        task[taskCount ++] = new TCPChatServerThreadTask (serverSocket);
    }
}
public static void main (String[] args) throws IOException
{       
    TCPChatServerThread e = new TCPChatServerThread ();
}
}

将 Java TCP 套接字聊天程序转换为 .net C# TCP 聊天程序

一种可行的策略:

  1. 将代码粘贴到 C# IDE 中。
  2. 更正语法错误
  3. 查找错误,如未知类/方法 xyz
  4. 查看 c# 的 API-Javadoc 等效项,并查找应该与 Java 类执行相同操作的 c# 类/方法,并相应地编辑代码。
  5. 测试它。