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

标签 c# java tcp

我有一个 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 ();
}
}

最佳答案

一种可行的策略:

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

关于c# - 将 Java TCP 套接字聊天程序转换为 .net C# TCP 聊天程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5567024/

相关文章:

c# - 在模块化 Prism WPF 应用程序中,我应该在哪里放置公共(public)字符串资源和公共(public) XAML ResourceDictionary?

java - 如何防止调用者捕获我的异常

java - 运行应用程序时,字符串无法转换为 JSONObject 错误

c - TCP 套接字是否以与发送数据相同的方式接收数据?

c# - JSON 友好的数据库?

c# - 如何更改 ASP.NET Core 中资源文件的命名空间?

java - 当使用 Smack 4.1.0 API 作为 Google 的 GCM CCS 的 XMPP 客户端时,SecurityMode.required 不工作

linux - 如何绑定(bind)到只有一个网络接口(interface)(Linux)的所有地址?

c# - 从托管代码调用非托管方法

java - 如何通过 PHP 代码运行 shell 命令?