Java szerver Java Kliensekkel tud kommunikálni, de C# Kliensekkel nem, miért?
Java Szerver programoódja:
// Java implementation of Server side
// It contains two classes : Server and ClientHandler
// Save file as Server.java
import java.io.*;
import java.util.*;
import java.net.*;
// Server class
public class Server
{
// Vector to store active clients
//static Vector<ClientHandler> ar = new Vector<>();
public static final int MAX_CLIENTS = 100000;
public static ClientHandler[] ar = new ClientHandler[MAX_CLIENTS];
public static int getempty() {
for(int i = 0; i < MAX_CLIENTS; i++) if(ar[i] == null) return i;
return -1;
}
public static void main(String[] args) throws IOException
{
// server is listening on port 5000
Date date = new Date();
String[] timearray = date.toString().split(" ");
String time = timearray[3];
int port = 8251;
ServerSocket ss = new ServerSocket(port);
System.out.println("Server successfully started on port " + port + " at: " + time + " Max Clients: " + MAX_CLIENTS);
Socket s;
for(int i = 0; i < MAX_CLIENTS; i++) ar[i] = null;
// running infinite loop for getting
// client request
while (true)
{
// Accept the incoming request
s = ss.accept();
//--->important //System.out.println("New client request received : " + s);
// obtain input and output streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//--->important //System.out.println("Creating a new handler for this client...");
// Create a new handler object for handling this request.
int index = getempty();
//if(index == -1) throw new EOFException();
date = new Date();
timearray = date.toString().split(" ");
time = timearray[3];
System.out.println("client " + index + " connected" + " at: " + time);
ClientHandler mtch = new ClientHandler(s, index, "client " + index, dis, dos);
// Create a new Thread with this object.
Thread t = new Thread(mtch);
//--->important //System.out.println("Adding this client to active client list");
// add this client to active clients list
ar[index] = mtch;
// start the thread.
t.start();
}
}
}
// ClientHandler class
class ClientHandler implements Runnable
{
Scanner scn = new Scanner(System.in);
Date date = new Date();
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
int index;
boolean isloggedin;
// constructor
public ClientHandler(Socket s, int index, String name,
DataInputStream dis, DataOutputStream dos) {
this.dis = dis;
this.dos = dos;
this.name = name;
this.index = index;
this.s = s;
this.isloggedin=true;
}
@Override
public void run() {
String received;
try {
this.dos.writeUTF("Client number: " + this.name);
StringBuilder sb = new StringBuilder();
String strLine = "";
List<String> list = new ArrayList<String>();
try {
//BufferedReader br = new BufferedReader(new FileReader("/Desktop/questions.txt"), "UTF8");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/Desktop/questions.txt"), "UTF8"));
while (strLine != null)
{
strLine = br.readLine();
sb.append(strLine);
sb.append(System.lineSeparator());
strLine = br.readLine();
if (strLine==null)
break;
list.add(strLine);
}
this.dos.writeUTF(Arrays.toString(list.toArray()));
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
} catch(IOException e) {
e.printStackTrace();
}
while (true)
{
try
{
received = dis.readUTF();
System.out.println(received);
if(received.equals("logout")){
this.isloggedin=false;
this.s.close();
break;
}
String MsgToSend;
String recipient;
try {
StringTokenizer st = new StringTokenizer(received, "#");
MsgToSend = st.nextToken();
recipient = st.nextToken();
} catch (NoSuchElementException e) {
for (ClientHandler mc : Server.ar) {
if(mc == null) continue;
mc.dos.writeUTF(this.name+": "/*+this.name+*/+received);
}
continue;
}
for (ClientHandler mc : Server.ar)
{
if(mc == null) continue;
if (mc.name.equals(recipient) && mc.isloggedin==true)
{
mc.dos.writeUTF(this.name+": "/*+this.name+*/+MsgToSend);
break;
}
}
} catch (IOException e) {
Date date = new Date();
String[] timearray = date.toString().split(" ");
String time = timearray[3];
System.out.println(this.name + " disconnected" + " at: " + time);
break;
}
}
try
{
this.dis.close();
this.dos.close();
Server.ar[this.index] = null;
}catch(IOException e){
e.printStackTrace();
}
}
}
Java Client programkódja:
// Java implementation for multithreaded chat client
// Save file as Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
final static int ServerPort = 5000;
public static void main(String args[]) throws UnknownHostException, IOException
{
Scanner scn = new Scanner(System.in);
// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");
// establish the connection
Socket s = new Socket(ip, ServerPort);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// sendMessage thread
Thread sendMessage = new Thread(new Runnable()
{
@Override
public void run() {
while (true) {
// read the message to deliver.
String msg = scn.nextLine();
try {
// write on the output stream
dos.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
// readMessage thread
Thread readMessage = new Thread(new Runnable()
{
@Override
public void run() {
while (true) {
try {
// read the message sent to this client
String msg = dis.readUTF();
System.out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
sendMessage.start();
readMessage.start();
}
}
Ez így működik, de ha C# Klienst csatlakoztatok rá, akkor a C# kliens megkapja az üzenetet, rendesen ki is írja, de ő nem tud üzenetet küldeni.
C# Kliens programkódja:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Boolean cantConnect = false;
IPAddress ipAddr = IPAddress.Parse("localhost");
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 5000);
Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(localEndPoint);
Console.WriteLine("Client connected (local)!");
//sender.RemoteEndPoint.ToString();
/*Thread sndmsg = new Thread(() =>
{*/
//SendMsg(sender);
/*});*/
//Thread sndmsg = new Thread(SendMsg);
//sndmsg.Start();
//Thread rdmsg = new Thread())=>ReadMsg(sender));
Thread rdmsg = new Thread(() => {
ReadMsg(sender);
});
rdmsg.Start();
SendMsg(sender);
}
catch
{
cantConnect = true;
Console.WriteLine("Can't connect to the server at the time.");
}
//Console.ReadLine();
}
private static void SendMsg(Socket sender)
{
while (true)
{
String message = Console.ReadLine();
byte[] messageSent = Encoding.ASCII.GetBytes(message);
int byteSent = sender.Send(messageSent);
}
}
private static void ReadMsg(Socket sender)
{
while (true)
{
byte[] messageReceived = new byte[1024];
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}", Encoding.ASCII.GetString(messageReceived, 0, byteRecv));
}
}
}
}
/*class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("80.99.176.178");
int port = 8251;
TcpClient client = new TcpClient();
client.Connect(ip, port);
Console.WriteLine("client connected!!");
NetworkStream ns = client.GetStream();
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
string s;
while (!string.IsNullOrEmpty((s = Console.ReadLine())))
{
byte[] buffer = Encoding.ASCII.GetBytes(s);
ns.Write(buffer, 0, buffer.Length);
}
client.Client.Shutdown(SocketShutdown.Send);
thread.Join();
ns.Close();
client.Close();
Console.WriteLine("disconnect from server!!");
Console.ReadKey();
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
Console.Write(Encoding.ASCII.GetString(receivedBytes, 0, byte_count));
}
}
}
/*
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 5000;
TcpClient client = new TcpClient();
client.Connect(ip, port);
Console.WriteLine("client connected!!");
NetworkStream ns = client.GetStream();
Thread thread = new Thread(o => ReceiveData((TcpClient)o));
thread.Start(client);
string s;
while (!string.IsNullOrEmpty((s = Console.ReadLine())))
{
byte[] buffer = Encoding.ASCII.GetBytes(s);
ns.Write(buffer, 0, buffer.Length);
}
client.Client.Shutdown(SocketShutdown.Send);
thread.Join();
ns.Close();
client.Close();
Console.WriteLine("disconnect from server!!");
Console.ReadKey();
}
static void ReceiveData(TcpClient client)
{
NetworkStream ns = client.GetStream();
byte[] receivedBytes = new byte[1024];
int byte_count;
while ((byte_count = ns.Read(receivedBytes, 0, receivedBytes.Length)) > 0)
{
Console.Write(Encoding.ASCII.GetString(receivedBytes, 0, byte_count));
}
}
}
*/
Nézzétek el kérlek, hogy hülye vagyok ehhez.
Köszönöm a gyors választ!
Sajnos ez tényleg így van, és emiatt ragadtam le ezen a ponton :(
Ez ugye nem munkahelyi feladat? Ha igen, akkor hogy vettek fel?
GitHub gistről hallottál?
stackoverflow.com?
Hűha :D A Java és a C végpontok sem kompatibilisek egymással, azért, mert máshogy tárolják a sztringet. És lám, egyik sem Microsoft-technológia.
A hálózati kommunikáció bár elviekben platform- és nyelvfüggetlen, de az implementáció koránt sem az. Ha a szerver úgy küldi a string-et, hogy "alma\0", akkor a kliens hiába vár arra, hogy "4alma", nem azt fogja kapni. Pedig a szerver azt küldte, hogy alma, a kliens pedig azt várja, hogy alma. Fejlesztőként ismerned kell a kliens és a szerver által küldött adat adatábrázolását és közös formára kell hozni, tartva a hálózati szabványos bájtsorrendet.
Kapcsolódó kérdések:
Minden jog fenntartva © 2024, www.gyakorikerdesek.hu
GYIK | Szabályzat | Jogi nyilatkozat | Adatvédelem | Cookie beállítások | WebMinute Kft. | Facebook | Kapcsolat: info(kukac)gyakorikerdesek.hu
Ha kifogással szeretne élni valamely tartalommal kapcsolatban, kérjük jelezze e-mailes elérhetőségünkön!