List clients connected to server
Is there a way to list the number of Clients connected to a Server?
Also, how can two Clients talk to each other using the Server as their mediator?
Example: Client1 sends "Hello Client2" to Client2 via the Server.
Client2 sends "Hi there Client1" to Client1 via the Server.
Thanks
Well, you wrote the server?
If so, then you can add code to the server to keep track of all the currently connected clients. You might wish to store them in a Set or a List or a Map. And you can add code to print the contents of that Set or List or Map.
For the second part, just like the first, it's a rather broad question. "How" to have them talk to each other? You need to define your requirements. For instance, will there always only be two clients, and they just talk to each other? Or could there be any number of clients and any one can talk to any other, lik with chat? What part of what you want do you not understand? The basic idea is that the client sends to the server, and the server forwards on to the other clien. I don't really know what you're asking.
You might try googling for java chat code or something. I'm sure you'll find lots of samples.
Similar Messages
-
What privileges for the DB account used by client connect to server?
Hello, After I installed the SBO server packages, I found that it must set DB account in the client side.
I had tried 'sa' account, it works. but I thought we should not leave the super account in each client side.
So I want to know what privileges should be assiged to the account in SQL Server?
Or somewhere already have documents to say how to build up the client account.
thanks.Hi,
You may check: What privileges for the DB account used by client connect to server?
Thanks,
Gordon -
[Solved] MPD clients connect to server too long first time
When my system start mpd clients cannot connect to server a long(10-15 seconds or more) for some reason.
Same time internet connection and network seems to be ok.
So, It's look like I run mpc for example and it get stuck. This problem is new. 2-4 weeks or less.
I've tried use user and global config without any success.
Mpd config now look like this:
music_directory "/home/neg/music"
playlist_directory "/home/neg/.mpd/playlists"
db_file "/home/neg/.mpd/mpd.db"
log_file "/home/neg/.mpd/mpd.log"
pid_file "/home/neg/.mpd/mpd.pid"
state_file "/home/neg/.mpd/mpdstate"
sticker_file "/home/neg/.mpd/sticker.sql"
user "neg"
bind_to_address "localhost"
port "6600"
input {
plugin "curl"
save_absolute_paths_in_playlists "yes"
metadata_to_use "artist,album,title,track,name,genre,date"
follow_inside_symlinks "yes"
connection_timeout "2"
filesystem_charset "UTF-8"
input {
plugin "curl"
audio_output {
type "pulse"
name "Local Music Player Daemon"
mixer_type "hardware"
server "127.0.0.1"
My netctl profile looks like this:
Description='A basic dhcp ethernet connection'
Interface=enp6s0
Connection=ethernet
SkipNoCarrier=yes
IP=static
DNS=('192.168.1.1')
Address=('192.168.1.35/24')
Gateway='192.168.1.1'
## for DHCPv6
#IP6=dhcp
## for IPv6 autoconfiguration
#IP6=stateless
System start looks almost normal. USB reinit after uefi takes a lot of time sometimes, but it's not critical.
[~] >> PAGER= systemd-analyze blame
7.483s systemd-udev-settle.service
543ms zfs-mount.service
443ms systemd-modules-load.service
121ms [email protected]
100ms [email protected]
83ms [email protected]
68ms systemd-logind.service
68ms lm_sensors.service
59ms alsa-restore.service
57ms zfs-share.service
38ms systemd-vconsole-setup.service
25ms polkit.service
24ms [email protected]
18ms ntpd.service
14ms systemd-udev-trigger.service
14ms avahi-daemon.service
13ms systemd-binfmt.service
13ms mnt-home.mount
12ms systemd-tmpfiles-setup-dev.service
12ms dev-hugepages.mount
10ms dev-mqueue.mount
10ms systemd-remount-fs.service
10ms sys-kernel-debug.mount
9ms proc-sys-fs-binfmt_misc.mount
8ms systemd-tmpfiles-setup.service
6ms systemd-update-utmp.service
5ms systemd-journal-flush.service
5ms boot-efi.mount
5ms systemd-random-seed.service
4ms kmod-static-nodes.service
4ms systemd-udevd.service
3ms var-cache-davfs2.mount
3ms var-cache-pkgfile.mount
3ms udisks.service
3ms var-cache-pacman.mount
2ms rtkit-daemon.service
1ms var-tmp.mount
1ms systemd-sysctl.service
1ms zfs-import-cache.service
1ms systemd-user-sessions.service
937us sys-kernel-config.mount
911us tmp.mount
Whole system config
[~] >> inxi -FC
System: Host: unreal Kernel: 3.18.2-2-ARCH x86_64 (64 bit) Desktop: N/A Distro: Arch Linux
Machine: System: ASUS product: All Series
Mobo: ASUSTeK model: SABERTOOTH Z97 MARK 1 version: Rev 1.xx
Bios: American Megatrends version: 0901 date: 05/08/2014
CPU: Quad core Intel Core i7-4790K CPU (-HT-MCP-) cache: 8192 KB flags: (lm nx sse sse2 sse3 sse4_1 sse4_2 ssse3 vmx)
Clock Speeds: 1: 4000.00 MHz 2: 4000.312 MHz 3: 4000.625 MHz 4: 4000.00 MHz 5: 4005.156 MHz 6: 4000.156 MHz 7: 4000.781 MHz 8: 4001.718 MHz
Graphics: Card: NVIDIA GM204 [GeForce GTX 980] X.Org: 1.16.3 driver: nvidia Resolution: [email protected]
GLX Renderer: GeForce GTX 980/PCIe/SSE2 GLX Version: 4.4.0 NVIDIA 343.36
Audio: Card-1: NVIDIA GM204 High Definition Audio Controller Sound: ALSA ver: k3.18.2-2-ARCH
Card-3: Creative driver: USB Audio
Network: Card-1: Realtek RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller driver: r8169
IF: enp6s0 state: up speed: 1000 Mbps duplex: full mac: 10:c3:7b:96:22:ef
Card-2: Intel Ethernet Connection (2) I218-V driver: e1000e
IF: eno1 state: down mac: 40:16:7e:e9:08:e1
Drives: HDD Total Size: 2378.5GB (20.0% used) 1: id: /dev/sda model: WDC_WD1003FZEX size: 1000.2GB
2: id: /dev/sdb model: PLEXTOR_PX size: 128.0GB 3: id: /dev/sdc model: ST3250312AS size: 250.1GB
4: id: /dev/sdd model: WDC_WD1003FZEX size: 1000.2GB
Partition: ID: / size: 89G used: 29G (35%) fs: ext4
Sensors: System Temperatures: cpu: 32.0C mobo: 34.0C gpu: 40C
Fan Speeds (in rpm): cpu: N/A fan-1: 0 fan-2: 0 fan-3: 0 fan-4: 0 fan-5: 0 fan-6: 0
Info: Processes: 424 Uptime: 2 min Memory: 2166.0/15993.2MB Client: Shell (zsh) inxi: 1.9.14
I've tried ::1 addr, sockets etc, nothing gets better.
Also I've tried to upgrade mpd to git or downgrade.
Last edited by Neg (2015-01-28 11:36:46)Rasi wrote:have you checked, if pulseaudio was running at that time already?
Yes, pulseaudio seems to be ok at that moment.
Also I have such thing in the log ~2 minutes
Jan 19 09:17 : client: [142] opened from 127.0.0.1:38434
Jan 19 09:17 : client: [142] closed
Jan 19 09:17 : client: [143] opened from 127.0.0.1:38435
Jan 19 09:17 : client: [143] closed
Jan 19 09:17 : client: [144] opened from 127.0.0.1:38436
Jan 19 09:17 : client: [144] closed
Jan 19 09:17 : client: [145] opened from 127.0.0.1:38437
Jan 19 09:17 : client: [145] closed
Jan 19 09:17 : client: [146] opened from 127.0.0.1:38438
Jan 19 09:17 : client: [146] closed
Jan 19 09:17 : client: [147] opened from 127.0.0.1:38439
Jan 19 09:17 : client: [147] closed
When daemon seems to be ok
[~] >> systemctl --user status mpd2
● mpd2.service - Music Player Daemon
Loaded: loaded (/home/neg/.config/systemd/user/mpd2.service; disabled)
Active: active (running) since Mon 2015-01-19 09:15:59 MSK; 1min 59s ago
Main PID: 1947 (mpd)
CGroup: /user.slice/user-1000.slice/[email protected]/mpd2.service
└─1947 /usr/bin/mpd --no-daemon /home/neg/.mpd.conf
Jan 19 09:15:59 unreal systemd[953]: Started Music Player Daemon.
Also I've tried to set port manually in ncmpcpp, then log messages are NOT gone.
I've already tried alsa-only config. Same issue.
When daemon is "running" clients of it are not response ~1-2 minute.
Last edited by Neg (2015-01-19 06:26:15) -
Blocking client connection, if server down
Hi,
is there a way for a client connection (an io socket, not by using nio channel) to block for a server, if the server is currently down?
ThanksThere's much more to this than the OP realizes:
1) if the server is down before the client could establish a connection,
the client has to keep retrying to make a connection.
2) if the server goes down while the client was waiting/reading for some
data, the connection is lost, the partial data must be kept or thrown
away depending on the communication protocol and the client should
repeat step 1) again.
3) if the server goes down while the client was writing to the server, the
write fails and the entire shebang should be restarted at step 1) again.
Personally I wouldn't bother and simply spit out a "connection lost,
please try again later" towards the general direction of the user.
kind regards,
Jos -
Callconnector advanced client connects to server only randomly
Hi,
I just installed scc server and 20 call connector advanced clients at a customer site. Everything worked on the installation.
Installed all the licenses ok.
I just received the following email from the client:
"A number of staff including myself are experiencing difficulty logging on to the Cisco Smart Call Connect system each morning. When we try to log on we get a message saying network error as the systems goes through the motions of trying to connect. After the systems has made 5 attempts to log on a message box pops up saying unable to connect to server. We are trying all the usual solutions to correct the problem ie. Restart and shut down etc. This is successful only sometimes and often we have to try several times. One of our ladies in the Accounts Department, Sally Pan has tried 4 or 5 times this morning to log on and is still unable to connect. In my case today after the 4th attempt I was able to connect."
The call connector server is always on and is installed on a win7 32bit 4gb ram system with static ip.
I can not see why would this happen.
How should I proceed troubleshooting this issue?
Another question: The callconnector advanced clients installations are on PCs that get ip address via dhcp. I know I had to input the ip address of the pc when I installed the advanced client. Does this have anything to do with it (i.e. does advanced client need to be installed to a pc with statically assigned ip address, or it does not matter)?Anthony,
It helps if you state what product and what version you are using. It appears as though
you are using Java System Message Queue. If so you need to set the
imqBrokerHostName attribute on the ConnectionFactory (imqAddressList is also
supported on later versions). See the Java Client Developer's Guide:
http://docs.sun.com/app/docs/coll/MessageQueue_2005Q1
A quick way is to pass the property on the command line:
java -DimqBrokerHostName=yourserver . . . -
How to change names in "favorite servers" list of Connect-to-Server
I've got a bunch of often-used servers saved in the list that shows up when I do "apple-K" (Finder's "Connect to Server"). but they're entered as IP addresses; I'd like to rename them so that I can actually recognize which one is which without having to look up the IP address in a list. Is there any way to customize this list to edit how the various frequently-used servers appear there?
MikeThe simplest solution would be to remove the server connections you don't want, then just re-connect to them using the name.
The recent servers are stored in ~/Library/Recent Servers/ and you can selectively remove them from there. -
Problem with client connect to server
Hello
I'm having problems trying to connect a Windows NT client to an Oracle 8.1.5.0.2 server running on
Redhat linux 6.1
I've setup the listener, which seems to allow a sqlplus client running on the server to connect to the
database through the listener.
<snip>
$ sqlplus scott/tiger@8idb
SQL*Plus: Release 8.1.5.0.0 - Production on Mon Apr 10 16:44:57 2000
(c) Copyright 1999 Oracle Corporation. All rights reserved.
Connected to:
Oracle8i Release 8.1.5.0.2 - Production
With the Java option
PL/SQL Release 8.1.5.0.0 - Production
SQL>
</snip>
Listener.log
<snip>
10-APR-00 16:44:57 *
(CONNECT_DATA=(SERVICE_NAME=8idb)(CID=(PROGRAM=)(HOST=dbserver)(USER=oracle))) *
(ADDRESS=(PROTOCOL=tcp)(HOST=10.0.0.10)(PORT=2816)) * establish * 8idb * 0
<snip>
But when I try to test the connection from the NT client using "Net8 Easy Config"
<snip>
Initializing first test to use userid: scott, password: tiger
Attempting to connect using userid: scott
The test did not succeed.
ORA-12571: TNS:packet writer failure
There may be an error in the fields entered,
or the server may not be ready for a connection.
</snip>
Even though I have the following entry in the listener.log.
<snip>
10-APR-00 16:58:37* (CONNECT_DATA=(SERVICE_NAME=8idb)(CID=(PROGRAM=C:\Program
Files\Oracle\jre\1.1.7\bin\jrew.exe)(HOST=NTclient)(USER=NTuser))) *
(ADDRESS=(PROTOCOL=tcp)(HOST=10.0.0.20)(PORT=2465)) * establish * 8idb * 0
</snip>
Though sqlnet.log is logging the follow
<snip>
Fatal NI connect error 12537, connecting to:
(LOCAL=NO)
VERSION INFORMATION:
TNS for Linux: Version 8.1.5.0.0 - Production
Oracle Bequeath NT Protocol Adapter for Linux: Version 8.1.5.0.0 - Production
TCP/IP NT Protocol Adapter for Linux: Version 8.1.5.0.0 - Production
Time: 10-APR-00 16:58:37
Tracing not turned on.
Tns error struct:
nr err code: 0
ns main err code: 12537
TNS-12537: TNS:connection closed
ns secondary err code: 0
nt main err code: 0
nt secondary err code: 0
nt OS err code: 0
</snip>
The listener.ora is as follows
<snip>
listener=
(description=
(address_list=
(address=(protocol=tcp)(host=10.0.0.10)(port=1521))
sid_list_listener=(sid_list=
(sid_desc=
(global_dbname=8idb)
(sid_name=8idb)
(oracle_home=/home/oracle/product/8.1.5)
</snip>
Clients Tnsnames.ora file
<snip>
# Generated by Oracle Net8 Assistant
8IDB=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(PORT = 1521)(HOST = 10.0.0.10))
(CONNECT_DATA =
(SERVICE_NAME = 8idb)
</snip>
Any Help would be greatly appreciated
Thanks
Regards
Tom
nullHi Hasan,
Firstly, please make sure that the software is compatible with the Windows Server 2012. Have you updated this software to the latest version?
Secondly, please check if the software is listening on the proper port. To verify this, please use the command below:
netstat -an
Also, please disable the firewall and try again.
Best regards.
Steven Lee
TechNet Community Support -
Non-Domain joined clients connect to server initially but cannot connect via Launchpad
Running SBS 2011 Essentials in a small office. Running XP/Vista/7 clients. All working fine until we swapped routers. Old router died, new router was installed.
Now all domain-joined PC's connect as normal, but all NON-Domain-Joined PC's cannot access the server via the launchpad. I get the "The server appears to be offline. Do you want to sign in to offline mode?" box.
Tried removing PC from the SBS Dashboard, uninstalling the connector from the client, restarting client, and reinstalling the connector. I can install the connector (using
http://<server ip>/connect , but not http://<servername>/connect
). Connector installs but it still tells me the server is offline when trying to use dashboard or launchpad on the client.
Note: I can add a network location or Map a network drive to ther server after inputting my network password from Windows.
Any Services to check? Firewalls exceptions to ensure? Advice?
EDIT: Dashboard on Server shows Client, sometimes as online, sometimes as offline.Sounds like name resolution issue to me.
Are all your clients set to use the IP of the Essentials Server for their primary DNS?
Robert Pearman SBS MVP
itauthority.co.uk |
Title(Required)
Facebook |
Twitter |
Linked in |
Google+ -
Hi all,
At one of client installation, I am required to every time use change server and give server ip address.
Whenever I login next to SAP B1 2007 B, it will not display company list, and I have to use Change server option everytime and change it to server ip from (local)
Can anybody tell me what I have to verify and change so that at Client PC SAP permanantly remembers the Server IP/Server Name
BR
Samir GandhiDear Samir,
In order to try to resolve the issue, please do the following steps :-
1. Go to Add/Remove Program --> Uninstall SAP Business One Client.
2. Go to C:\Program Files\SAP, then take a backup of the SAP Business One Folder and
then delete the SAP Business One folder.
3. Go to Start --> Run --> %UserProfile%\AppData\Local\SAP\
Then delete the SAP Business One Folder.
4. Now reinstall the SAP Business One Client application from the B1_SHR.
Now you can login and enter all the details information and then log out from SAP Business One
application. You can open the application again and check this issue.
Note : Please make sure that the Windows user has read and write access to the above two folders
as per step (2) and (3).
Regards,
Rakesh Pati
SAP Business One Forum Team. -
Clients connected to server freeze after while
We have a XServe an several Mac and Linux clients. The xserve mainly hosts the user directories (via afp for Mac- and NFS for Linux-Clients). In addition web-services and the iCal-server is running.
Everything was running fine for weeks. But recently I encountered a strange problem:
After working on a mobile account for a while (on a MacBook Pro) the machine becomes totally unresponsive (Beach-Ball-Everywhere). The Dock sooner or later always completely freezes. If I try to start an application like Terminal.app from the Dock (before it got frozen) then the icon gets an question-mark. All this happens on different user accounts.
This is completely strange as everything was working fine for quite some time. I am most interested in two things:
1) has anyone encountered any similar symptoms?
2) I am not quite sure, but maybe the trouble started after I added a SSL Certificate (but that's just an assumption)Of course I can not say for sure that it is no hardware defect but honestly I do not think so. Right after I posted my problem I disabled SSL for Open Directory (via ServerAdmin). So far everything works fine. So could be that this was the source for the problem?
At the moment I don't see an alternative for searching the problem by trial and error. My biggest hope is to find somebody with a similar problem. -
Different client connect server but get same IP??
i am doing a server for multiplayer game. when the client connect to server, server need to keep it IP. but why my server always get same IP for every connected client? my code is as below
public class CommServer {
private Vector clients = new Vector(); // a list of all connected clients
ServerSocket server; // the server
private static int INTPORT=9999;
public static void main(String args[]) {
CommServer myCS = new CommServer(INTPORT);
public CommServer(int port) {
startServer(port);
private void startServer(int port) {
try {
// --- create a new server
server = new ServerSocket(port);
// --- while the server is active...
while(true) {
// --- listen for new client connections
Socket socket = server.accept();
CSClient client = new CSClient(this, socket);
writeActivity(client.getIP() + " connected to the server.");
// --- start the client thread
client.start();
} catch(IOException ioe) {
writeActivity("Server Error...Stopping Server");
// kill this server
killServer();
public class CSClient extends Thread {
private Thread thrThis; // client thread
private Socket socket; // socket for connection
private CommServer server;
protected BufferedReader in; // captures incoming messages
protected PrintWriter out; // sends outgoing messages
public CSClient(CommServer server, Socket socket) {
this.server = server;
this.socket = socket;
this.ip = socket.getInetAddress().getHostAddress();
// --- initialize the reader and writer
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch(IOException ioe) {
killClient();
public String getIP() {
return ip;
}please help.. thankshi, thanks for reply.
yes, i am trying to connect from different macnine
that have different IP address.
how to check if it asign same external IP toclient?
can it be configure to assign different IP?what he means is, if you run your server at location
A, and all your clients from location B, with the
internet in between, and a single router/switch
serving internet connections to the clients at the B
location, then the server at the A location will see
the external IP of the site B router, not the
individual IPs of the clients behind the router
(since those IPs are only for internal network usage
behind the router)
in short, do you test with multiple clients from one
internet connection? then it would be logical that
they present the same IP to the server. The best (and
most realistic) way to test would be with multiple
clients from multiple locations / internet connectionsok.thanks.
so is it possible for me to get the client machine ip but not the IP for the router? because i will hav multiple user from same location access the server at the same time. -
Hi all,
My boss use iPhone, iPad, MacBook Air (Mac Mail client), MacPro (Mac Mail client) connect Exchange Serve 2010 to receive emails. All clients are okay except MacBook Air, the Mac Mail client cannot receive the latest emails from Exchange Server, but it can receive (sync) the emails after one hour. The other clients can receive the latest email after Exchange Server receive new emails immediately.
In this period, the MacBook Air can receive the other IMAP, POP3 and webmail from ISP normally. I tried to set 5 mins to check emails or manual check email from Exchange Server. However, the latest email still delay one hour.......... .
I dumped a screenshot for Mac Mail setting for Exchange Server and a Log file.
could anyone help me to solve this issue?
ThanksI am not sure what the user has the check for new messages set for but mail does arrive as short as 2 minutes. It does however arrive on his iphone immediately first.
-
Disconnecting clients from Streaming Server
Hello,
We have Streaming Server installed to stream online-seminars to the clients. We want to manually disconnect some clients during the translation while leaving others online. What is the way to do it? Clients connect to server by opening a web-page on the other web-server with embedded flash player which has the source streamer uri rtmp://our_server/live.
Thank you,
Olga Butygina.Спасибо за ответ!
У нас как раз php-сайт c данными о клиентах в mysql, так что предлагаемый вариант - то что надо. Одна проблема: мы используем уже готовый плеер (http://www.longtailvideo.com/players/jw-flv-player/) и не задумывались о разработке собственного флэшового плеера.
Разреши задать тебе пару вопросов.
1. Такой плеер, способный общаться с php-сервером, можно написать на Flex в свободном IDE или же требуется Flash Professional? Насколько я знаю, во Flash уже есть готовый компонент FLVPlayBack, можно ли без него обойтись во Flex?
2. С помощью Loadvars можно также посылать серверу информацию о запуске проигрывателя для пополнения счетчика просмотров или есть более простой способ внедрить такой посыльщик запроса в обычный swf, содержащий видео?
С уважением,
Ольга Бутыгина. -
How to list IP address from client on the Server (TCP/IP CLIENT SERVER COMMUNICATION)
Excuse me,
In this project I want to ask how to add list IP from client that connect to server.
I have edited slightly the project.
'SERVER
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Reflection
Public Class ServerForm
Private _Listener As TcpListener
Private _Connections As New List(Of ConnectionInfo)
Private _ConnectionMonitor As Task
Private Sub Button_Checked(sender As System.Object, e As System.EventArgs) Handles StartStopButton.CheckedChanged
If StartStopButton.Checked Then
StartStopButton.Text = "Stop"
StartStopButton.Image = My.Resources.StopServer
_Listener = New TcpListener(IPAddress.Any, CInt(PortTextBox.Text))
_Listener.Start()
Dim monitor As New MonitorInfo(_Listener, _Connections)
ListenForClient(monitor)
_ConnectionMonitor = Task.Factory.StartNew(AddressOf DoMonitorConnections, monitor, TaskContinuationOptions.LongRunning)
Else
StartStopButton.Text = "Start:"
StartStopButton.Image = My.Resources.StartServer
CType(_ConnectionMonitor.AsyncState, MonitorInfo).Cancel = True
_Listener.Stop()
_Listener = Nothing
End If
End Sub
Private Sub PortTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles PortTextBox.Validating
Dim deltaPort As Integer
If Not Integer.TryParse(PortTextBox.Text, deltaPort) OrElse deltaPort < 1 OrElse deltaPort > 65535 Then
MessageBox.Show("Port number between 1 and 65535", "Invalid Port Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
PortTextBox.SelectAll()
e.Cancel = True
End If
End Sub
Private Sub ListenForClient(monitor As MonitorInfo)
Dim info As New ConnectionInfo(monitor)
_Listener.BeginAcceptTcpClient(AddressOf DoAcceptClient, info)
End Sub
Private Sub DoAcceptClient(result As IAsyncResult)
Dim monitorinfo As MonitorInfo = CType(_ConnectionMonitor.AsyncState, MonitorInfo)
If monitorinfo.Listener IsNot Nothing AndAlso Not monitorinfo.Cancel Then
Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)
monitorinfo.Connections.Add(info)
info.AcceptClient(result)
ListenForClient(monitorinfo)
info.AwaitData()
Dim doUpdateConnectionCountLabel As New Action(AddressOf UpdateConnectionCountLabel)
Invoke(doUpdateConnectionCountLabel)
End If
End Sub
Private Sub DoMonitorConnections()
Dim doAppendOutput As New Action(Of String)(AddressOf AppendOutput)
Dim doUpdateConnectionCountLabel As New Action(AddressOf UpdateConnectionCountLabel)
Dim monitorInfo As MonitorInfo = CType(_ConnectionMonitor.AsyncState, MonitorInfo)
Me.Invoke(doAppendOutput, "Server Started")
Do
Dim lostCount As Integer = 0
For index As Integer = monitorInfo.Connections.Count - 1 To 0 Step -1
Dim info As ConnectionInfo = monitorInfo.Connections(index)
If info.Client.Connected Then
If info.DataQueue.Count > 0 Then
Dim messageBytes As New List(Of Byte)
While info.DataQueue.Count > 0
Dim value As Byte
If info.DataQueue.TryDequeue(value) Then
messageBytes.Add(value)
End If
End While
Me.Invoke(doAppendOutput, "Message from IP: " + System.Text.Encoding.ASCII.GetString(messageBytes.ToArray))
End If
Else
monitorInfo.Connections.Remove(info)
lostCount += 1
End If
Next
If lostCount > 0 Then
Invoke(doUpdateConnectionCountLabel)
End If
_ConnectionMonitor.Wait(1)
Loop While Not monitorInfo.Cancel
For Each info As ConnectionInfo In monitorInfo.Connections
info.Client.Close()
Next
monitorInfo.Connections.Clear()
Invoke(doUpdateConnectionCountLabel)
Me.Invoke(doAppendOutput, "Server Stoped")
End Sub
Private Sub UpdateConnectionCountLabel()
ConnectionCountLabel.Text = String.Format("{0} Connections", _Connections.Count)
End Sub
Private Sub AppendOutput(message As String)
If RichTextBox1.TextLength > 0 Then
RichTextBox1.AppendText(ControlChars.NewLine)
End If
RichTextBox1.AppendText(message)
RichTextBox1.ScrollToCaret()
End Sub
Private Sub ClearButton_Checked(sender As Object, e As EventArgs) Handles ClearButton.CheckedChanged
If ClearButton.Checked Then
RichTextBox1.Clear()
End If
End Sub
End Class
Public Class MonitorInfo
Private _listener As TcpListener
Public ReadOnly Property Listener As TcpListener
Get
Return _listener
End Get
End Property
Private _connections As List(Of ConnectionInfo)
Public ReadOnly Property Connections As List(Of ConnectionInfo)
Get
Return _connections
End Get
End Property
Public Property Cancel As Boolean
Public Sub New(tcpListener As TcpListener, connectionInfoList As List(Of ConnectionInfo))
_listener = tcpListener
_connections = connectionInfoList
End Sub
End Class
Public Class ConnectionInfo
Private _monitor As MonitorInfo
Public ReadOnly Property Monitor As MonitorInfo
Get
Return _monitor
End Get
End Property
Private _Client As TcpClient
Public ReadOnly Property Client As TcpClient
Get
Return _Client
End Get
End Property
Private _DataQueue As System.Collections.Concurrent.ConcurrentQueue(Of Byte)
Public ReadOnly Property DataQueue As System.Collections.Concurrent.ConcurrentQueue(Of Byte)
Get
Return _DataQueue
End Get
End Property
Private _Stream As NetworkStream
Public ReadOnly Property Stream As NetworkStream
Get
Return _Stream
End Get
End Property
Public Sub New(monitor As MonitorInfo)
_monitor = monitor
_DataQueue = New System.Collections.Concurrent.ConcurrentQueue(Of Byte)
End Sub
Private _LastReadLength As Integer
Public ReadOnly Property LastReadLength As Integer
Get
Return _LastReadLength
End Get
End Property
Private _Buffer(63) As Byte
Public Sub AcceptClient(result As IAsyncResult)
_Client = _monitor.Listener.EndAcceptTcpClient(result)
If _Client IsNot Nothing AndAlso _Client.Connected Then
_Stream = _Client.GetStream
End If
End Sub
Public Sub AwaitData()
_Stream.BeginRead(_Buffer, 0, _Buffer.Length, AddressOf DoReadData, Me)
End Sub
Private Sub DoReadData(result As IAsyncResult)
Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)
Try
If info.Stream IsNot Nothing AndAlso info.Stream.CanRead Then
info._LastReadLength = info.Stream.EndRead(result)
For Index As Integer = 0 To _LastReadLength - 1
info._DataQueue.Enqueue(info._Buffer(Index))
Next
'info.SendMessage("Data Diterima " & info._LastReadLength & " Bytes")
info.SendMessage("reply form server: " & info._LastReadLength & " Bytes")
For Each otherInfo As ConnectionInfo In info.Monitor.Connections
If Not otherInfo Is info Then
otherInfo.SendMessage(System.Text.Encoding.ASCII.GetString(info._Buffer))
End If
Next
info.AwaitData()
Else
info.Client.Close()
End If
Catch ex As Exception
info._LastReadLength = -1
End Try
End Sub
Private Sub SendMessage(message As String)
If _Stream IsNot Nothing Then
Dim messageData() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
Stream.Write(messageData, 0, messageData.Length)
End If
End Sub
End Class
'CLIENT
Imports System.Net
Imports System.Net.Sockets
Public Class ClientForm
Private _Connection As ConnectionInfo
Private _ServerAddress As IPAddress
Private Sub ClientForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ValidateChildren()
End Sub
Private Sub ConnectButton_Checked(sender As Object, e As System.EventArgs) Handles ConnectButton.CheckedChanged
If ConnectButton.Checked Then
If _ServerAddress IsNot Nothing Then
ConnectButton.Text = "Disconnect"
ConnectButton.Image = My.Resources.StopServer
Try
_Connection = New ConnectionInfo(_ServerAddress, CInt(PortTextBox.Text), AddressOf InvokeAppendOutput)
_Connection.AwaitData()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Connecting to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ConnectButton.Checked = False
End Try
Else
MessageBox.Show("Invlid IP Server", "Cannt Connect to Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ConnectButton.Checked = False
End If
Else
ConnectButton.Text = "Connect"
ConnectButton.Image = My.Resources.StartServer
If _Connection IsNot Nothing Then _Connection.Close()
_Connection = Nothing
End If
End Sub
Private Sub SendButton_Click(sender As System.Object, e As System.EventArgs) Handles SendButton.Click
If _Connection IsNot Nothing AndAlso _Connection.Client.Connected AndAlso _Connection.Stream IsNot Nothing Then
Dim buffer() As Byte = System.Text.Encoding.ASCII.GetBytes(InputTextBox.Text)
_Connection.Stream.Write(buffer, 0, buffer.Length)
End If
End Sub
Private Sub ServerTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles IPTextBox.Validating
_ServerAddress = Nothing
Dim remoteHost As IPHostEntry = Dns.GetHostEntry(IPTextBox.Text)
If remoteHost IsNot Nothing AndAlso remoteHost.AddressList.Length > 0 Then
For Each deltaAddress As IPAddress In remoteHost.AddressList
If deltaAddress.AddressFamily = AddressFamily.InterNetwork Then
_ServerAddress = deltaAddress
Exit For
End If
Next
End If
If _ServerAddress Is Nothing Then
MessageBox.Show("Cannot resolve Server Address", "invalid Server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
IPTextBox.SelectAll()
e.Cancel = True
End If
End Sub
Private Sub PortTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles PortTextBox.Validating
Dim deltaPort As Integer
If Not Integer.TryParse(PortTextBox.Text, deltaPort) OrElse deltaPort < 1 OrElse deltaPort > 65535 Then
MessageBox.Show("Port number between 1 and 65535", "invalid Port number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
PortTextBox.SelectAll()
e.Cancel = True
End If
End Sub
Private Sub InvokeAppendOutput(message As String)
Dim doAppendOutput As New Action(Of String)(AddressOf AppendOutput)
Me.Invoke(doAppendOutput, message)
End Sub
Private Sub AppendOutput(message As String)
If RichTextBox1.TextLength > 0 Then
RichTextBox1.AppendText(ControlChars.NewLine)
End If
RichTextBox1.AppendText(message)
RichTextBox1.ScrollToCaret()
End Sub
Private Sub ButtonClear_Click(sender As Object, e As EventArgs) Handles ButtonClear.Click
RichTextBox1.Clear()
InputTextBox.Clear()
End Sub
End Class
Public Class ConnectionInfo
Private _AppendMethod As Action(Of String)
Public ReadOnly Property AppendMethod As Action(Of String)
Get
Return _AppendMethod
End Get
End Property
Private _Client As TcpClient
Public ReadOnly Property Client As TcpClient
Get
Return _Client
End Get
End Property
Private _Stream As NetworkStream
Public ReadOnly Property Stream As NetworkStream
Get
Return _Stream
End Get
End Property
Private _LastReadLength As Integer
Public ReadOnly Property LastReadLength As Integer
Get
Return _LastReadLength
End Get
End Property
Private _Buffer(63) As Byte
Public Sub New(address As IPAddress, port As Integer, append As Action(Of String))
_AppendMethod = append
_Client = New TcpClient
_Client.Connect(address, port)
_Stream = _Client.GetStream
End Sub
Public Sub AwaitData()
_Stream.BeginRead(_Buffer, 0, _Buffer.Length, AddressOf DoreadData, Me)
End Sub
Public Sub Close()
If _Client IsNot Nothing Then _Client.Close()
_Client = Nothing
_Stream = Nothing
End Sub
Private Sub DoreadData(result As IAsyncResult)
Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)
Try
If info._Stream IsNot Nothing AndAlso info._Stream.CanRead Then
info._LastReadLength = info._Stream.EndRead(result)
If info._LastReadLength > 0 Then
Dim message As String = System.Text.Encoding.ASCII.GetString(info._Buffer)
info._AppendMethod(message)
End If
info.AwaitData()
End If
Catch ex As Exception
info._LastReadLength = -1
info._AppendMethod(ex.Message)
End Try
End Sub
End Class
//ScreenShot server
http://prntscr[dot]com/5t1ol3
//Screenshot client
http://prntscr[dot]com/5t1odj
source: code[dot]msdn[dot]microsoft[dot]com/windowsdesktop/Simple-Multi-User-TCPIP-43cc3b44I have a similar chat application. When the user attempts to connect, instead of sending a simple string, the client sends a serialized object(xml string) with all relevant login and session information, this includes the user's IP address. Once the server
receives said information, depending on the type of TCP broadcast (a custom enumerated type) information from one user may be passed to a single user, or distributed to many users.
If it helps, here is the TCPBroadcast object I use. But in order for your server to understand it, you kind of have to build your server and client somewhat around it.
Option Strict On
Option Explicit On
Option Infer Off
Namespace TCPChat
Public Class TCPBroadcast
Public Property Message As String
Public Property BroadCastTime As DateTime
Public Property DestUser As String
Public Property OriginUser As String
Public Property PasswordHash As String
Public Property BroadcastSourceIP As String
Public Property BroadCastType As TCPBroadcastType
Public Property LoginUserName As String
Public Property FailureReason As String
Public Function XmlEncoding() As String
Dim serializer As New Xml.Serialization.XmlSerializer(GetType(TCPBroadcast))
Dim XML As String = String.Empty
Using memStream As New IO.MemoryStream
Using xmlWriter As New Xml.XmlTextWriter(memStream, System.Text.Encoding.UTF8) With _
{.Indentation = 4, .Formatting = System.Xml.Formatting.Indented}
serializer.Serialize(xmlWriter, Me)
End Using
XML = System.Text.Encoding.UTF8.GetString(memStream.ToArray)
End Using
Return XML
End Function
Public Function ToBinary() As Byte()
Return System.Text.Encoding.UTF8.GetBytes(Me.XmlEncoding)
End Function
Public Shared Function FromBinary(binary As Byte()) As DeserializationResult
Dim xml As String = System.Text.Encoding.UTF8.GetString(binary)
Return FromXML(xml)
End Function
Public Shared Function FromXML(xml As String) As DeserializationResult
Dim DeserializationResult As New DeserializationResult
DeserializationResult.Error = False
Try
Dim deserializer As New Xml.Serialization.XmlSerializer(GetType(TCPBroadcast))
Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(xml)
Using memStream As New IO.MemoryStream(buffer)
DeserializationResult.tcpBroadCast = CType(deserializer.Deserialize(memStream), TCPBroadcast)
End Using
Catch ex As Exception
DeserializationResult.Error = True
DeserializationResult.ErrorMessage = ex.ToString
DeserializationResult.AttemptedXML = xml
End Try
Return DeserializationResult
End Function
Public Class DeserializationResult
Public [Error] As Boolean
Public ErrorMessage As String
Public tcpBroadCast As TCPBroadcast
Public AttemptedXML As String
Sub New()
End Sub
End Class
Public Enum TCPBroadcastType
AdministrativeMessage
AuthenticationFailure
AuthenticationSuccess
ChatBroadcast
CredentialsRequest
Credentials
DisconnectedByServer
KeepAlive
PrivateMessage
ServerMessage
SystemMessage
UnableToProcessRequest
End Enum
End Class
End Namespace
“If you want something you've never had, you need to do something you've never done.”
Don't forget to mark
helpful posts and answers
! Answer an interesting question? Write a
new article
about it! My Articles
*This post does not reflect the opinion of Microsoft, or its employees. -
How to make the client connect to the server at the command prompt?
I found this code on IBM's website, it was a training session on servers and clients using java.
The code compiles fine and the server seems to start up properly when I use java Server 5000. I think whats happening is the server is running and listening for a connection on port 5000.
When I try to run the client I get the following error.
Exception in thread "main" java.lang.NoSuchMethodError: main
I see a start() method but no main. As far as I know, applications should all have main, it seems as if the person who wrote this kinda confused applets with application. Not that I would really know what happened.
If you have time, could you tell me if there's an easy fix for this? I would love to have this client/server working if it isn't too much trouble. As I have looked all over the net for a free client/server applet that will actually let me see the java code and none of the free ones do allow getting to their source.
Most of them allow you to customize them somewhat but also have built in advertising that can't be removed.
This is the closest I have come to finding one that lets me look under the hood. But alas it doesn't work out of the box and I don't know what to do to fix it.
Heres the code: Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
// The ServerSocket we'll use for accepting new connections
private ServerSocket ss;
// A mapping from sockets to DataOutputStreams. This will
// help us avoid having to create a DataOutputStream each time
// we want to write to a stream.
private Hashtable outputStreams = new Hashtable();
// Constructor and while-accept loop all in one.
public Server( int port ) throws IOException {
// All we have to do is listen
listen( port );
private void listen( int port ) throws IOException {
// Create the ServerSocket
ss = new ServerSocket( port );
// Tell the world we're ready to go
System.out.println( "Listening on "+ss );
// Keep accepting connections forever
while (true) {
// Grab the next incoming connection
Socket s = ss.accept();
// Tell the world we've got it
System.out.println( "Connection from "+s );
// Create a DataOutputStream for writing data to the
// other side
DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
// Save this stream so we don't need to make it again
outputStreams.put( s, dout );
// Create a new thread for this connection, and then forget
// about it
new ServerThread( this, s );
// Get an enumeration of all the OutputStreams, one for each client
// connected to us
Enumeration getOutputStreams() {
return outputStreams.elements();
// Send a message to all clients (utility routine)
void sendToAll( String message ) {
// We synchronize on this because another thread might be
// calling removeConnection() and this would screw us up
// as we tried to walk through the list
synchronized( outputStreams ) {
// For each client ...
for (Enumeration e = getOutputStreams(); e.hasMoreElements(); ) {
// ... get the output stream ...
DataOutputStream dout = (DataOutputStream)e.nextElement();
// ... and send the message
try {
dout.writeUTF( message );
} catch( IOException ie ) { System.out.println( ie ); }
// Remove a socket, and it's corresponding output stream, from our
// list. This is usually called by a connection thread that has
// discovered that the connectin to the client is dead.
void removeConnection( Socket s ) {
// Synchronize so we don't mess up sendToAll() while it walks
// down the list of all output streamsa
synchronized( outputStreams ) {
// Tell the world
System.out.println( "Removing connection to "+s );
// Remove it from our hashtable/list
outputStreams.remove( s );
// Make sure it's closed
try {
s.close();
} catch( IOException ie ) {
System.out.println( "Error closing "+s );
ie.printStackTrace();
// Main routine
// Usage: java Server <port>
static public void main( String args[] ) throws Exception {
// Get the port # from the command line
int port = Integer.parseInt( args[0] );
// Create a Server object, which will automatically begin
// accepting connections.
new Server( port );
}CLIENT:
import java.io.*;
import java.net.*;
public class ServerThread extends Thread
// The Server that spawned us
private Server server;
// The Socket connected to our client
private Socket socket;
// Constructor.
public ServerThread( Server server, Socket socket ) {
// Save the parameters
this.server = server;
this.socket = socket;
// Start up the thread
start();
// This runs in a separate thread when start() is called in the
// constructor.
public void run() {
try {
// Create a DataInputStream for communication; the client
// is using a DataOutputStream to write to us
DataInputStream din = new DataInputStream( socket.getInputStream() );
// Over and over, forever ...
while (true) {
// ... read the next message ...
String message = din.readUTF();
// ... tell the world ...
System.out.println( "Sending "+message );
// ... and have the server send it to all clients
server.sendToAll( message );
} catch( EOFException ie ) {
// This doesn't need an error message
} catch( IOException ie ) {
// This does; tell the world!
ie.printStackTrace();
} finally {
// The connection is closed for one reason or another,
// so have the server dealing with it
server.removeConnection( socket );
}Thanks for your time.CLIENT:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client extends Panel implements Runnable
// Components for the visual display of the chat windows
private TextField tf = new TextField();
private TextArea ta = new TextArea();
// The socket connecting us to the server
private Socket socket;
// The streams we communicate to the server; these come
// from the socket
private DataOutputStream dout;
private DataInputStream din;
// Constructor
public Client( String host, int port ) {
// Set up the screen
setLayout( new BorderLayout() );
add( "North", tf );
add( "Center", ta );
// We want to receive messages when someone types a line
// and hits return, using an anonymous class as
// a callback
tf.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
processMessage( e.getActionCommand() );
// Connect to the server
try {
// Initiate the connection
socket = new Socket( host, port );
// We got a connection! Tell the world
System.out.println( "connected to "+socket );
// Let's grab the streams and create DataInput/Output streams
// from them
din = new DataInputStream( socket.getInputStream() );
dout = new DataOutputStream( socket.getOutputStream() );
// Start a background thread for receiving messages
new Thread( this ).start();
} catch( IOException ie ) { System.out.println( ie ); }
// Gets called when the user types something
private void processMessage( String message ) {
try {
// Send it to the server
dout.writeUTF( message );
// Clear out text input field
tf.setText( "" );
} catch( IOException ie ) { System.out.println( ie ); }
// Background thread runs this: show messages from other window
public void run() {
try {
// Receive messages one-by-one, forever
while (true) {
// Get the next message
String message = din.readUTF();
// Print it to our text window
ta.append( message+"\n" );
} catch( IOException ie ) { System.out.println( ie ); }
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class ClientApplet extends Applet
public void init() {
String host = getParameter( "192.168.1.47" );
int port = Integer.parseInt( getParameter( "5000" ) );
setLayout( new BorderLayout() );
add( "Center", new Client( host, port ) );
}Sorry about that. Now when I run an html file with this applet I just get the x in the corner.
Thanks for looking.
Maybe you are looking for
-
Mac mini 2012 crashes and restarts
Hi, I've read similar issues to this, however here goes: I've just bought a second hand mac mini, late 2012, quad-core 2.3 ghz i7 running Yosemite, that's just been upgraded to 16 gb ram. I don't have the original rams sadly. The computer keeps crash
-
Reg calling Transaction code in Webdynpro ABAP
Hi All, Can I call Transaction code in Webdynpro ABAP Portal Application. If so, how can this be possible? Can anybody give me a lead? Thanks. Kumar Saurav.
-
ITunes 10 keeps launching, can't quit
Since I upgraded to version 10, I've had 2 days where iTunes launches on it's own and no matter how many times I Quit, it keeps re-launching automatically. Today, it was when we visited a Flash site: http://www.howtotrainyourdragon.com/ and on the ot
-
Want to integrate weblogic server with eclipse
Hi, I am trying to integrate weblogic with eclipse. so that i can start the weblogic server from my eclipse. can you please give me a point to a location from where i can download the plugin. And also i want my eclipse to support the j2ee development
-
Photoshop to InDesign - What works? What should be done in InDesign versus Photoshop?
Hello! I have been using Photoshop for years, and before very recently any work I've ever done started in Photoshop - whether it be a logo or newsletter layout. From there I learn whichever tricks I need to for whatever the customer has asked - ie: