- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我需要将字符串消息从 Java 程序实时发送到 C# 程序。Internet 上有很多示例,但您找不到任何适合我的目的的东西(可能)是 Java 客户端(套接字代码)和 C# 服务器(套接字代码)。谢谢。
最佳答案
好的,我已经在我的一个项目中这样做了,所以这里是:
免责声明:部分代码(实际上只有一点点)基于 nakov 聊天服务器。
另请注意,我对所有以 UTF-8 格式发送和接收的消息进行解码和编码。
类:服务器
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server
{
private static void createAndShowGUI() {
//Create and set up the window
}
public static final int LISTENING_PORT = 2002;
public static void main(String[] args)
{
// Open server socket for listening
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(LISTENING_PORT);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
//System.out.println("Server started on port " + LISTENING_PORT);
}
catch (IOException se)
{
System.err.println("Can not start listening on port " + LISTENING_PORT);
se.printStackTrace();
System.exit(-1);
}
// Start ServerDispatcher thread
ServerDispatcher serverDispatcher = new ServerDispatcher();
// Accept and handle client connections
while (true)
{
try
{
Socket socket = serverSocket.accept();
ClientInfo clientInfo = new ClientInfo();
clientInfo.mSocket = socket;
ClientListener clientListener =
new ClientListener(clientInfo, serverDispatcher);
ClientSender clientSender =
new ClientSender(clientInfo, serverDispatcher);
clientInfo.mClientListener = clientListener;
clientInfo.mClientSender = clientSender;
clientListener.start();
clientSender.start();
serverDispatcher.addClient(clientInfo);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
类消息分发器:
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.*;
public class ServerDispatcher
{
private Vector mMessageQueue = new Vector();
private Vector<ClientInfo> mClients = new Vector<ClientInfo>();
public synchronized void addClient(ClientInfo aClientInfo) {
mClients.add(aClientInfo);
}
public synchronized void deleteClient(ClientInfo aClientInfo) {
int clientIndex = mClients.indexOf(aClientInfo);
if (clientIndex != -1)
mClients.removeElementAt(clientIndex);
}
private synchronized void sendMessageToAllClients(String aMessage)
{
for (int i = 0; i < mClients.size(); i++) {
ClientInfo infy = (ClientInfo) mClients.get(i);
infy.mClientSender.sendMessage(aMessage);
}
}
public void sendMessage(ClientInfo aClientInfo, String aMessage) {
aClientInfo.mClientSender.sendMessage(aMessage);
}
}
类:ClientInfo
/**
*
* ClientInfo class contains information about a client, connected to the server.
*/
import java.awt.List;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
public class ClientInfo
{
public int userID=-1;
public Socket mSocket = null;
public ClientListener mClientListener = null;
public ClientSender mClientSender = null;
}
类ClientListner:
/**
* ClientListener class is purposed to listen for client messages and
* to forward them to ServerDispatcher.
*/
import java.io.*;
import java.net.*;
public class ClientListener extends Thread {
private ServerDispatcher mServerDispatcher;
private ClientInfo mClientInfo;
private BufferedReader mIn;
private String message;
private String decoded = null;
public ClientListener(ClientInfo aClientInfo,
ServerDispatcher aServerDispatcher) throws IOException {
mClientInfo = aClientInfo;
mServerDispatcher = aServerDispatcher;
Socket socket = aClientInfo.mSocket;
mIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
/**
* Until interrupted, reads messages from the client socket, forwards them
* to the server dispatcher and notifies the server dispatcher.
*/
public void run() {
message = "";
while (!isInterrupted()) {
try {
message = mIn.readLine();
if (message == null)
break;
try {
decoded = URLDecoder.decode(message, "UTF-8");
} catch (UnsupportedEncodingException e)
e.printStackTrace();
}
mServerDispatcher.sendMessage(mClientInfo, decoded);
}
catch (IOException e) {
break;
}
}
// Communication is broken. Interrupt both listener and sender threads
mClientInfo.mClientSender.interrupt();
mServerDispatcher.deleteClient(mClientInfo);
}
}
类:ClientSender
/**
* Sends messages to the client. Messages are stored in a message queue. When
* the queue is empty, ClientSender falls in sleep until a new message is
* arrived in the queue. When the queue is not empty, ClientSender sends the
* messages from the queue to the client socket.
*/
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientSender extends Thread
{
private Vector mMessageQueue = new Vector();
private ServerDispatcher mServerDispatcher;
private ClientInfo mClientInfo;
private PrintWriter mOut;
public ClientSender(ClientInfo aClientInfo, ServerDispatcher aServerDispatcher)
throws IOException
{
mClientInfo = aClientInfo;
mServerDispatcher = aServerDispatcher;
Socket socket = aClientInfo.mSocket;
mOut = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
}
/**
* Adds given message to the message queue and notifies this thread
* (actually getNextMessageFromQueue method) that a message is arrived.
* sendMessage is called by other threads (ServeDispatcher).
*/
public synchronized void sendMessage(String aMessage)
{
mMessageQueue.add(aMessage);
notify();
}
/**
* @return and deletes the next message from the message queue. If the queue
* is empty, falls in sleep until notified for message arrival by sendMessage
* method.
*/
private synchronized String getNextMessageFromQueue() throws InterruptedException
{
while (mMessageQueue.size()==0)
wait();
String message = (String) mMessageQueue.get(0);
mMessageQueue.removeElementAt(0);
return message;
}
/**
* Sends given message to the client's socket.
*/
private void sendMessageToClient(String aMessage)
{
String encoded;
try {
encoded = URLEncoder.encode(aMessage,"UTF-8");
mOut.println(encoded);
mOut.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Until interrupted, reads messages from the message queue
* and sends them to the client's socket.
*/
public void run()
{
try {
while (!isInterrupted()) {
String message = getNextMessageFromQueue();
sendMessageToClient(message);
}
} catch (Exception e) {
// Commuication problem
break;
}
// Communication is broken. Interrupt both listener and sender threads
mClientInfo.mClientListener.interrupt();
mServerDispatcher.deleteClient(mClientInfo);
}
}
好的,这是java代码,现在是c#代码
使用的变量:
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
private Thread thrMessaging;
private IPAddress ipAddr;
private bool Connected;
功能:智能连接:
private void InitializeConnection()
{
// Parse the IP address
string ipAdress = "XXX.XXX.XXX.XXX";
ipAddr = IPAddress.Parse(ipAdress);
// Start a new TCP connections to the chat server
tcpServer = new TcpClient();
try
{
tcpServer.Connect(ipAddr, 2002);
swSender = new StreamWriter(tcpServer.GetStream());
// Start the thread for receiving messages and further communication
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
Connected=true;
}
catch (Exception e2)
{
MessageBox.Show(e2.ToString());
}
}
}
功能:接收消息
private void ReceiveMessages()
{
// Receive the response from the server
srReceiver = new StreamReader(tcpServer.GetStream());
while (Connected)
{
String con = srReceiver.ReadLine();
string StringMessage = HttpUtility.UrlDecode(con, System.Text.Encoding.UTF8);
processMessage(StringMessage);
}
}
函数:proceesMessage:
private void processMessage(String p)
{
// do something with the message
}
函数发送消息:
private void SendMessage(String p)
{
if (p != "")
{
p = HttpUtility.UrlEncode(p, System.Text.Encoding.UTF8);
swSender.WriteLine(p);
swSender.Flush();
}
}
这就是您在 Java 服务器和 C# 客户端之间进行通信所需的全部内容。如果您有任何问题,请随时在此处发布。
关于c# - 套接字:将字符串从 Java 发送到 C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999180/
我使用下拉菜单提供一些不同的链接,但我希望这些链接在同一选项卡中打开,而不是在新选项卡中打开。这是我找到的代码,但我对 Javascript 非常缺乏知识 var urlmenu = docume
我对 javascript 不太了解。但我需要一个垂直菜单上的下拉菜单,它是纯 JavaScript,所以我从 W3 复制/粘贴脚本:https://www.w3schools.com/howto/t
我已经坐了 4 个小时,试图让我的导航显示下 zipper 接垂直,但它继续水平显示它们。我无法弄清楚为什么会发生这种情况或如何解决它。 如果有人能告诉我我做错了什么,我将不胜感激。我有一个潜移默化的
我正在尝试创建选项卡式 Accordion 样式下拉菜单。我使用 jQuery 有一段时间了,但无法使事件状态达到 100%。 我很确定这是我搞砸的 JS。 $('.service-button').
对于那些从未访问过 Dropbox 的人,这里是链接 https://www.dropbox.com/ 查看“登录”的下拉菜单链接。我如何创建这样的下 zipper 接? 最佳答案 这是 fiddle
我正在制作一个 Liferay 主题,但我在尝试设计导航菜单的样式时遇到了很多麻烦。我已经为那些没有像这样下拉的人改变了导航链接上的经典主题悬停功能: .aui #navigation .nav li
如果您将鼠标悬停在 li 上,则会出现一个下拉菜单。如果您将指针向下移至悬停时出现的 ul,我希望链接仍然带有下划线,直到您将箭头从 ul 或链接移开。这样你就知道当菜单下拉时你悬停在哪个菜单上。 知
我有一个带有多个下拉菜单的导航栏。因此,当我单击第一个链接时,它会打开下拉菜单,但是当我单击第二个链接时,第一个下拉菜单不会关闭。 (所以如果用户点击第二个链接我想关闭下拉菜单) // main.js
我正在尝试制作一个导航下拉菜单(使用 Bootstrap 3),其中链接文本在同一行上有多个不同的对齐方式。 在下面的代码中,下拉列表 A 中的链接在 HTML 中有空格字符来对齐它们,但是空白被忽略
我希望有人能帮我解决这个 Bootstrap 问题,因为我很困惑。 有人要求我在底部垂直对齐图像和其中包含图像的链接。 我面临的问题是他们还希望链接在链接/图像组合上具有 pull-right,这会杀
我正在构建一个 Rails 应用程序,并希望指向我的类的每个实例的“显示”页面的链接显示在“索引”页面的下拉列表中。我目前正在使用带有 options_from_collection_for_sele
我有以下 Bootstrap3 导航菜单 ( fiddle here )。我想设置“突出显示”项及其子链接与下拉列表 1 和 2 链接不同的链接文本(和悬停)的样式。我还希望能够以不同于 Highli
我对导航栏中的下拉菜单有疑问。对于普通的导航链接(无下拉菜单),我将菜单文本放在 H3 中,但是当我尝试对下 zipper 接执行相同操作时,箭头不在标题旁边,而是在标题下方。我决定用 span 替换
我是一名优秀的程序员,十分优秀!