Java Socket Programming Example

By | 04月27日
Advertisement

Java Socket Programming Example

Sockets Example


Introduction

JAVA

Menu

Sockets

Text Files

CSS

CSS tutorial

LINUX

Commands


This example introduces you to Java socket programming. The server
listens for a connection. When a connection is established by a client. The
client can send data. In the current example the client sends the message "Hi
my server". To terminate the connection, the client sends the message "bye".
Then the server sends the message "bye" too. Finally the connection
is ended and the server waits for an other connection. The two programs should
be runned in the same machine. however if you want to run them in two different
machines, you may simply change the adress "localhost" by the IP adress
of the machine where you will run the server.

The server

import java.io.*; import java.net.*; public class Provider{   ServerSocket providerSocket;    Socket connection = null;   ObjectOutputStream out;     ObjectInputStream in;   String message;     Provider(){}    void run()  {       try{            //1. creating a server socket           providerSocket = new ServerSocket(2004, 10);            //2. Wait for connection            System.out.println("Waiting for connection");           connection = providerSocket.accept();           System.out.println("Connection received from " + connection.getInetAddress().getHostName());            //3. get Input and Output streams           out = new ObjectOutputStream(connection.getOutputStream());             out.flush();            in = new ObjectInputStream(connection.getInputStream());            sendMessage("Connection successful");           //4. The two parts communicate via the input and output streams             do{                 try{                    message = (String)in.readObject();                  System.out.println("client>" + message);                     if (message.equals("bye"))                      sendMessage("bye");                 }               catch(ClassNotFoundException classnot){                     System.err.println("Data received in unknown format");              }           }while(!message.equals("bye"));         }       catch(IOException ioException){             ioException.printStackTrace();      }       finally{            //4: Closing connection             try{                in.close();                 out.close();                providerSocket.close();             }           catch(IOException ioException){                 ioException.printStackTrace();          }       }   }   void sendMessage(String msg)    {       try{            out.writeObject(msg);           out.flush();            System.out.println("server>" + msg);         }       catch(IOException ioException){             ioException.printStackTrace();      }   }   public static void main(String args[])  {       Provider server = new Provider();       while(true){            server.run();       }   } }

The client

  import java.io.*; import java.net.*; public class Requester{   Socket requestSocket;   ObjectOutputStream out;     ObjectInputStream in;   String message;     Requester(){}   void run()  {       try{            //1. creating a socket to connect to the server             requestSocket = new Socket("localhost", 2004);          System.out.println("Connected to localhost in port 2004");          //2. get Input and Output streams           out = new ObjectOutputStream(requestSocket.getOutputStream());          out.flush();            in = new ObjectInputStream(requestSocket.getInputStream());             //3: Communicating with the server          do{                 try{                    message = (String)in.readObject();                  System.out.println("server>" + message);                     sendMessage("Hi my server");                    message = "bye";                    sendMessage(message);               }               catch(ClassNotFoundException classNot){                     System.err.println("data received in unknown format");              }           }while(!message.equals("bye"));         }       catch(UnknownHostException unknownHost){            System.err.println("You are trying to connect to an unknown host!");        }       catch(IOException ioException){             ioException.printStackTrace();      }       finally{            //4: Closing connection             try{                in.close();                 out.close();                requestSocket.close();          }           catch(IOException ioException){                 ioException.printStackTrace();          }       }   }   void sendMessage(String msg)    {       try{            out.writeObject(msg);           out.flush();            System.out.println("client>" + msg);         }       catch(IOException ioException){             ioException.printStackTrace();      }   }   public static void main(String args[])  {       Requester client = new Requester();         client.run();   } }

Similar Posts:

  • Java Socket、Hibernate独立使用

    有一个需求,需要用Java从Socekt写一个TCP服务供客户端使用,得保证长时间可靠运行,这类型的开发一般是做成什么形式的,写一个可以执行的jar,然后java -jar xx.jar吗? 还有,需要在上面用到数据库,计划用一个现成的ORM框架(比如Hibernate)来免去写sql的麻烦,在这样抛开容器独立运行的情况下Hibernate需要怎么配置,或者有其它相关的ORM框架推荐么? 谢谢! --cut-- kikong在2015-05-19 19:01:36回答到: A: 1)如果需要图形

  • java Socket tcp/ip 异步短连接单工模式

    使用java socket通信使用tcp/ip协议异步短连接单工模式. 主要是 单工模式不太理解. 单工模式是向单一方向发送不回流?只发送信息不接收信息,只接收信息不发送信息.是这样的吗? 是这样的话那我在我这边,创建个server和client端负责收发. --cut-- 暗雨西喧在2015-04-21 09:56:58回答到: 通过单线传输信息是串行数据通信的基础.数据通常是在两个站(点对点)之间进行传输,按照数据流的方向可分成三种传输模式:单工.半双工.全双工. 单工模式一般用在只向一个方

  • Socket Programming in C#--Getting Started

    Getting Started You can argue that one can overcome these shortcomings by multithreading meaning that one can spawn a new thread and let that thread do the polling which then notifies the main thread of the data. This concept could work well, but eve

  • 三步学会Java Socket编程

    三步学会Java Socket编程 http://developer.51cto.com 2009-02-04 09:45 佚名 Java8 我要评论(0) 摘要:所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过"套接字"向网络发出请求或者应答网络请求.本文将Java Socket编程分为三个学习步骤,逐一为您讲解. 标签:Java Socket Socket API Java编程 第一步 充分理解Socket 1.

  • Java Socket编程 - 获取WEB站点主页信息

    早就有想写一个Java Socket编程系列的文章,由于自己懒一直没动.决定从 今天开始,每周写一篇,从最简单的socket连接,到文件传输到协议实现,到 远程桌面控制,全面讲述Java socket编程的各个方面与各种技巧,从普通 socket到Java NIO. 本文算是第一篇,简述如何通过Java Socket获取网站的主页内容其中包括 如何获取本地机器名与IP地址,如何建立一个socket连接到远程WEB站点 如何使用HTTP GET方法获取网站主页内容与HTTP响应头.程序运行结果:

  • Java Socket基础(一)

    Java Socket基础 较基础的Java Socket通信样例! 一.长连接通信 客户端和服务端建立通道后,Socket一直开着.两端通过read()等待消息. 1)简易聊天 服务端可主动对各个客户端发送消息,而各客户端只能单独发送给服务端.当然,只要你愿意,在服务端改下,即可转发了. 附件解压工程ChatSocket,运行TestServer.TestClient即可.src下还有两批处理,详细看TestServer文件内注释了. 1.1)ChatServer.java /** * 长连接

  • java socket 多线程网络传输多个文件

    http://blog.csdn.net/njchenyi/article/details/9072845 java socket 多线程网络传输多个文件 2013-06-10 21:26 3596人阅读 评论(1) 收藏 举报 分类: JAVA(158) 由于需要研究了下用 java socket 传输文件,由于需要传输多个文件,因此,采用了多线程设计.客户端每个线程创建一个 socket 连接,每个 socket 连接负责传输一个文件,服务端的ServerSocket每次 accept 一个

  • java socket 聊天体会

    java socket 做一些 总结吧. 对于Server来说 ServerSocket server = new ServerSocket(8000);//端口号 Socket s = server.accept();//等待连接 InputStream in = s.getInputStream(); DataInputStream dis = new DataInputStream(in); OutputStream out = s.getOutputStream(); DataOutpu

  • linux c socket programming

    原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http://www.slideshare.net/Arbow/asynchronous-io-programming verygood C: Linux Socket Programming, TCP, a simple HTTP client http://coding.debuntu.org/c-linu

  • Java Socket重要参数讲解

    (转自http://www.cnblogs.com/ggjucheng/archive/2012/01/06/2314679.html) ( http://docs.oracle.com/javase/tutorial/java/package/summary-package.html) Java Socket的api可能很多人会用,但是Java Socket的参数可能很多人都不知道用来干嘛的,甚至都不知道有这些参数. backlog 用于ServerSocket,配置ServerSocket的

Tags: