How to send multiple objects from Client to Server
Hi
I have a simple Client - Server architecture. I am trying to send 5 objects from Client to the Server which the server would operate on.
In the past I've used PrintWriter to pass Strings from Client to Server but now when I am dealing with multiple Objects and PrintWriter not allowing sending of Arrays or ArrayList, how can I send these from the Client to the Server? What would be a good writer to use for this purpose?
Thanks!
Thanks, I am looking into ObjectOutputStream but from the API it appears I can only send 1 object at a time. I need to send 5 objects per transaction and then send the next group of 5 objects for another transaction.
Could you clarify some more on how to put these objects together as a single Object perhaps?
Thanks
Similar Messages
-
Sending an object from client to server always on button press
What I need is to send an object from client to server but I need to make server wait until another object is sent. What I have is the JFrame where you put the wanted name and surname, then you create a User object with these details and on button press you send this object to the server. I just can't hold the connection because when I send the first object, server doesn't wait for another button click and throws EOFexception. Creating the while loop isn't helpfull as well because it keeps sending the same object again and again. The code is here
public class ClientFrame extends JFrame {
private JButton btnSend;
private JTextField txfName;
private JTextField txfSurname;
public ClientFrame() {
this.setTitle(".. ");
Container con = this.getContentPane();
con.setLayout(new BorderLayout());
txfName = new JTextField("name");
txfSurname = new JTextField("surname");
btnSend = new JButton(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
SSLSocketFactory f =
(SSLSocketFactory) SSLSocketFactory.getDefault();
try {
SSLSocket c =
(SSLSocket) f.createSocket("localhost", 8888);
c.startHandshake();
OutputStream os = c.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
InputStream is = c.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
boolean done = false;
while (!done) {
String first = txfName.getText();
String last = txfSurname.getText();
User u = new User();
u.setFirstName(first);
u.setLastName(last);
oos.reset();
oos.writeObject(u);
String str = (String) ois.readObject();
if (str.equals("rcvdOK")) {
System.out.println("received on the server side");
} else if (str.equals("ERROR")) {
System.out.println("ERROR");
//oos.writeObject(confirmString);
oos.close();
os.close();
c.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClientFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
System.err.println(ex.toString());
btnSend.setText("send object");
con.add(btnSend, BorderLayout.PAGE_START);
con.add(txfName, BorderLayout.CENTER);
con.add(txfSurname, BorderLayout.PAGE_END);
this.pack();
setSize(200, 150);
setVisible(true);
public class TestServer {
public static void main(String[] args) {
try {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(ksName), ksPass);
KeyManagerFactory kmf =
KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, ctPass);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8888);
printServerSocketInfo(s);
SSLSocket c = (SSLSocket) s.accept();
InputStream is = c.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
OutputStream os = c.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
boolean done = false;
User u;
while(!done){
u = (User) ois.readObject();
String confirmString = "rcvdOK";
String errorString = "ERROR";
if (u != null) {
System.out.println(u.getFirstName() + " " + u.getLastName());
oos.writeObject(confirmString);
} else if (u == null) {
oos.writeObject(errorString);
is.close();
s.close();
c.close();
} catch (Exception e) {
System.err.println(e.toString());
}Thanks for any help, btw this doesnt need to be via ssl, the problem would be the same using only http. Please anyone help me:)
Edited by: Vencicek on 7.5.2012 2:19
Edited by: EJP on 7/05/2012 19:53
Edited by: Vencicek on 7.5.2012 3:36Current code fails because it's sending still the same entity again(using while loop)No it's not. You are creating a new User object every time around the loop.
which makes the system freezeWhich means that you are executing network code in the event thread. Don't do that, use a separate thread. At the moment you're doing all that sending inside the constructor for ClientFrame which is an even worse idea: you can never get out of there to the rest of your client program. This is a program design problem, not a networking problem.
and doesn't allow me to set new parameters of the new entityI do not understand.
I need to find a way to keep Server running even when the client doesn't send any data and wait until the client doesnt press the send button again to read a new object.That's exactly what happens. readObject() blocks until data is received. -
How to send multiple objects from appleto to servlet and vice versa
how can i send multiple objects(ArrayLists and String) from servlet to applet and applet to servlet?
Use an HTTPUrlConnection from the Applet to the Servlet to send data to the server, or request information from the servlet. To actually transfer the objects you will have to use a serialized version of the objects, almost always by wrapping the streams generated via the UrlConnection in ObjectOutputStream and ObjectInputStreams.
-
How to send an object from one application to another?
Hi all,
I have two applications over the same server. The first application needs to send an object to the other application.
I try to put the object as a session attribute, but in the moment that the second application tries to get the attribute, the attribute doesn't exist.
Does anybody now how can pass an object from the one application to the other?You can also use JMS
-
How to transfer passwords encrypted from client to server?
Hello dear community,
I have already some experience with programming and did a lot of web-software, but I never was facing the problem that passwords are transfered as plain text to the server when using a login-form.
For my front-end, I use Java ServerFaces 2.0.
I read a lot of hints like using a javascript based MD5 library and send the password as MD5 but this can be sniffed an decrypted easily.
Do you have some hints to easily implement a secure transfer of values from client to server?
best regards,
Bernigoose_fraba wrote:
and how to do that? how to configure etc.?Server specific. Read your server's documentation. -
How to send multiple idocs from WE19?
How to send 100 IDocs at a time using We19?
in other words, can we generate 100 IDocs from a single Idoc using We19
Thanks,
VenHi Venkat,
Check program RSEOUT00.
Hope this helps.
Regards
Lakshman -
How to send multiple objects in a ObjectOutputStream
1) I need to get more than one text field and send it to the servlet.
2) How do I keep the Objects seperate in the servlet when they get inputed. I have to so I can sabe them to seperate variables.
Applet Code
URL url = new URL("http://www.mysite.com/servlet/Hello");
URLConnection servletConnection = url.openConnection();
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestProperty("Content-Type","application/octet-stream");
ObjectOutputStream out = new ObjectOutputStream(servletConnection.getOutputStream());
//Gets data from text field
out.writeObject( (Object) cusNum.getText() ); //(Object)
// I need to get more than one text field and send it to the servlet.
out.flush();
out.close();Servlet Code
ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
String fromApplet = (String) inputFromApplet.readObject();
inputFromApplet.close();//Gets data from text fieldNo, this gets data from text field and writes it to the output.
out.writeObject( (Object) cusNum.getText() ); //(Object)So that writes one object.
// I need to get more than one text field and send it to the servlet. So do that.
String fromApplet = (String) inputFromApplet.readObject();Here you have read one object. If you want to read another, do so. -
How to send XML packet from external socket server to OSB
Hi folks,
How do I use external Socket Server(tcp) to send payload to OSB ?
I have configured the socket protocol in my OSB. I am also able to send and receive responses by testing my proxy services from OSB itself.
But now, we want to use some external socket (tcp)server to be able to fire some xml file and then receive response on OSB.
Please help
salilYou need to use a socket client application to send a message to a socket where your proxy is listening. For receiving a message at a socket, configure business service at OSB.
Regards,
Anuj -
How to send a message from server to a particular client
Hi all,
I need to send a message from one host to another host which are connected in local domain. Now I'm able to send a message from client to server and vice versa but what I need is the server should route that message which I send through one client to another host(client) .
How can I do that ?
Please give me some ideas how to do that .
Thanks in advance
Edited by: m.parthiban on Mar 5, 2008 1:20 PMejp, thanks for your reply . can you please explain me bit more by providing code snippet ?
This is what I have done till now :
MyServer:
package connection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
* @param args
public static void main(String[] args) {
String ss ="",temp ="";
Socket clientLink=null;
try {
ServerSocket sockServer = new ServerSocket(6000);
while(true) {
clientLink = sockServer.accept();
System.out.println("Connection Established");
InputStreamReader isr = new InputStreamReader(clientLink.getInputStream());
BufferedReader bufReader = new BufferedReader(isr);
// System.out.println("buf "+bufReader.readLine());
try {
while ((temp=bufReader.readLine())!=null) {
ss+=temp;
System.out.println("ss "+ss+"Temp "+temp );
System.out.println("Client > "+ss);
} catch (IOException e) {
System.out.println("while reading");
e.printStackTrace();
OutputStreamWriter osw = new OutputStreamWriter(clientLink.getOutputStream());
PrintWriter pw = new PrintWriter(osw,true);
pw.write("Welcome -by Server !!!");
pw.flush();
clientLink.shutdownOutput();
clientLink.close();
} catch (IOException e) {
System.out.println("Can't able to connect");
e.printStackTrace();
}MyClient:
package connection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JOptionPane;
public class MyClient {
* @param args
public static void main(String[] args) {
try {
String serverMsg="",temp="";
Socket client = new Socket("127.0.0.1",6000);
PrintWriter pw = new PrintWriter(client.getOutputStream(),true);
pw.write("Hi ,Accecpt me");
pw.flush();
// pw.close();
client.shutdownOutput();
InputStreamReader isr = new InputStreamReader(client.getInputStream());
BufferedReader bufRead = new BufferedReader(isr);
while ((temp=bufRead.readLine())!=null) {
serverMsg +=temp;
System.out.println("Server > "+serverMsg);
JOptionPane.showMessageDialog(null, serverMsg);
client.shutdownInput();
client.close();
} catch (IOException e) {
System.out.println("Failed to connect");
e.printStackTrace();
}Once again thanks for the time you spend to reply me. -
How can i send multiple sms from my iphone 4
how can i send multiple sms from my i phone 4
Turn Group Messaging (instructions in lin that follows) off and send the message to multiple recipients. The result may be dependent on your carrier. If manually keying in numbers rather than using contacts, use the return key after each number. http://support.apple.com/kb/HT5760
-
How to Send Multiple Plot XY Graph from LabVIEW to Microsoft Excel
The link below describes exactly what I would like to do, however the link to the solution/work around does not work.
Has anyone got an alternative solution?
http://digital.ni.com/public.nsf/allkb/CFD30D5E9C01AB5386256CFB0082AF3EPlease check the link again as it seems to be working fine now.
How to Send Multiple Plot XY Graphs from LabVIEW to Microsoft Excel:
http://digital.ni.com/public.nsf/allkb/CFD30D5E9C01AB5386256CFB0082AF3E
The standard Excel Insert Graph.vi cannot insert multiple XY Graphs to Microsoft Excel, so you will need to use the Report Generation Toolkit for Microsoft Office. You will find a link to an example program at the bottom of the page. I have also attached it below.
Attachments:
example.zip 35 KB -
how do I send multiple photos from ipad2
If you view the photos in thumbnail view, as opposed to full screen, then via the icon of the box with the arrow coming out of it at the top right of the app you should be able to select up to 5 photos and attach them to an email via the Email button towards the top left of the app (on iOS 5 it's via Share not Email).
-
How do I send multiple photos from my ipad3
How do I send multiple photos from my ipad3
Go to a Photo Album and in upper right is select button. Tap and select the photos you want to send and then in upper right lap on the outbox icon and then select email.
-
HT202724 How i can send multiple sms from mac without being a group message ?
How i can send multiple sms from mac without being a group message ?
Start new conversations, one for each recipient.
-
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.
Maybe you are looking for
-
How do you keep two users logged in at the same time?
How do I keep two users logged in at the same time to be able to access home sharing?
-
I have a Motorollo XOOM mult-card reader and it fits exactly into my Playbook,.However the Playbook does not recognise the card reader, and my photo card is too large to fit into my Blackberry phone so can I do something to make Playbook recognise t
-
Oracle: 10.2g with my_tab as (select 99999 player_id, 'John Smith' player_name, 'Bulls' team_name, 16 points, 1 sequence from dual union all select 99999 player_id, 'John Smith' player_name, 'Pistons' team_name, 4 points, 2 sequence f
-
Site Meter Issue on Safari, Firefox and Opera
Hi - Sorry if this should actually be a OS X question, but since it's a browser issue I thought this might be the place. I have several blogs that have Site Meter on them. When I view the blogs, the Site Meter "bugs" do not appear. When I try to acce
-
ICloud nightmare - kept agreeing to terms and conditions in circle
i have been agreeing to terms and condition for more than 100 Times . Come on Apple !!!! iCloud is not working now . Contacts are not syncing even though on the web it is there but i cannot download to the phone !!! Stop bluffing the world the status