Using Sockets in Java - Server
2008-04-25 02:13
483 查看
Download TCPEchoServer - 793 B
ServerSocket mySock = new ServerSocket(1234);
here the server will wait ("listen for") a connection from a client on port 1234
2.Put the server into a waiting state
Socket link = mySock.accept();
here the server waits indefinitely("blocks") for a client to connect with the help of accept method of class ServerSocket, class that will return a Socket object when a connection is made.
3.Set up input and output streams
Let's examine two methods : getInputStream and getOuputStream of class Socket.This methods are used to get references to streams associated with the socket returned in step 2.
These streams you will use later for communication with a client that has just made a connection.If you are not using a GUI application, you can wrap a Scanner object around the InputStream object, object that is returned by method getInputStream, in order to obtain string-oriented input, let's see how :
Scanner input = new Scanner(link.getInputStream());
In the same time we can wrap a PrintWriter object around the OutputStream object returned by method getOutputStream.We supply the PrintWriter constructor with a second argument of true, this argument will cause the output buffer to be flushed for every call of println, let's see how :
PrintWriter output = new PrintWriter(link.getOutputStream(),true);
4.Send and receive data
After you have set up your Scanner and PrintWriter objects, to send data and to receive is very straightforward.For this we have to use nextLine method for receiving data and println to send data, let's see how :
output.println("Awaiting data...");
String input = input.nextLine();
5.Close the connection (after completion of the dialogue)
link.close();
Look at this code :
Collapse
Introduction
In this article I will describe the steps to make a connection in Java using Sockets.Let's start to understand what is a communication created via TCP/IP...A communication link created via TCP/IP sockets is a connection-oriented link.This means that the connection between the server and client remains open throuhout the duration of the dialogue between the two and is only broken (under normal circumstances) when one end of the dialogue formally terminates the exchanges (via an agreed protocol)Using the code
1.Create a ServerSocket objectServerSocket mySock = new ServerSocket(1234);
here the server will wait ("listen for") a connection from a client on port 1234
2.Put the server into a waiting state
Socket link = mySock.accept();
here the server waits indefinitely("blocks") for a client to connect with the help of accept method of class ServerSocket, class that will return a Socket object when a connection is made.
3.Set up input and output streams
Let's examine two methods : getInputStream and getOuputStream of class Socket.This methods are used to get references to streams associated with the socket returned in step 2.
These streams you will use later for communication with a client that has just made a connection.If you are not using a GUI application, you can wrap a Scanner object around the InputStream object, object that is returned by method getInputStream, in order to obtain string-oriented input, let's see how :
Scanner input = new Scanner(link.getInputStream());
In the same time we can wrap a PrintWriter object around the OutputStream object returned by method getOutputStream.We supply the PrintWriter constructor with a second argument of true, this argument will cause the output buffer to be flushed for every call of println, let's see how :
PrintWriter output = new PrintWriter(link.getOutputStream(),true);
4.Send and receive data
After you have set up your Scanner and PrintWriter objects, to send data and to receive is very straightforward.For this we have to use nextLine method for receiving data and println to send data, let's see how :
output.println("Awaiting data...");
String input = input.nextLine();
5.Close the connection (after completion of the dialogue)
link.close();
Look at this code :
Collapse
public class TCPEchoServer { private static ServerSocket servSock; private static final int PORT = 1234; public static void main(String[] args) { System.out.println("Opening port.../n"); try { servSock = new ServerSocket(PORT); //Step 1. } catch(IOException ioEx) { System.out.println("Unable to attach to port!"); System.exit(1); } do { handleClient(); } while (true); } private static void handleClient() { Socket link = null; //Step 2. try { link = servSock.accept(); //Step 2. Scanner input = new Scanner(link.getInputStream()); //Step 3. PrintWriter output = new PrintWriter(link.getOutputStream(),true); //Step 3. int numMessages = 0; String message = input.nextLine(); //Step 4. while (!message.equals("***CLOSE***")) { System.out.println("Message received."); numMessages++; output.println("Message " + numMessages + ": " + message); //Step 4. message = input.nextLine(); } output.println(numMessages + " messages received."); //Step 4. } catch(IOException ioEx) { ioEx.printStackTrace(); } finally { try { System.out.println( "/n* Closing connection... *"); link.close(); //Step 5. } catch(IOException ioEx) { System.out.println("Unable to disconnect!"); System.exit(1); } } } }
History
This example represents the SERVER program, in next article (JavaSocketsClient.aspx) I will describe the CLIENT program, is almost the same.License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)相关文章推荐
- Connecting to LDAP server using JNDI in Java
- Connecting to LDAP server using JNDI in Java
- Using Sockets in Java - Client
- StandardServer.await: create[8005]java.net.BindException: Address already in use: JVM_Bind
- SecurityException when using SQL Server 2005 JDBC driver in WebSphere 6
- Update metadata value using server object model in sharepoint 2013
- Exception thrown by the agent : java.rmi.server.ExportException: Port already in use
- How to convert from string to datetime in sql server? - Sealyu - BlogJava
- Android java.lang.IllegalStateException: Already logged in to server.
- JavaServer Faces JSF in Action
- Socket Server in JavaME
- StandardServer.await: create[8005]: java.net.BindException: Address already in use: JVM_Bind java.ne
- Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
- Using MERGE in SQL Server to insert, update and delete at the same time
- Using mockito in java
- Java in Science: Data Interpolation and Extrapolation Using Numerical Methods of Polynomial Fittings
- Hadoop出现错误:WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable,解决方案
- Exception in thread "main" java.lang.NoClassDefFoundError: Server (wrong name: com/it/www/Server)
- Using DDL Triggers in SQL Server 2005 to Capture Schema Changes
- 启动tomcat时 错误: 代理抛出异常 : java.rmi.server.ExportException: Port already in use: 1099的解决办法