- 浏览: 1113259 次
文章分类
- 全部博客 (379)
- S2SH (16)
- stuts2 (0)
- java语言 (81)
- JSP (17)
- <html>元素 (11)
- javaweb (4)
- web容器 (3)
- ext (23)
- javaScript (48)
- ant (1)
- liferay (1)
- sql (9)
- css (42)
- 浏览器设置 (3)
- office_world (1)
- eclipse (4)
- 其它 (28)
- 操作系统 (5)
- android (6)
- Struts2 (11)
- RegEx (3)
- mysql (5)
- BigDATA (1)
- Node.js (1)
- Algorithm (10)
- Apache Spark (1)
- 数据库 (5)
- linux (2)
- git (1)
- Adobe (3)
- java语言,WebSocket (1)
- Maven (3)
- SHELL (1)
- XML (2)
- 数学 (2)
- Python (2)
- Java_mysql (1)
- ReactJS (6)
- 养生 (4)
- Docker (1)
- Protocols (3)
- java8 (2)
- 书籍 (1)
- Gradle (2)
- AngularJS (5)
- SpringMVC (2)
- SOAP (1)
- BootstrapCSS (1)
- HTTP协议 (1)
- OAuth2 (1)
最新评论
-
Lixh1986:
Java并发编程:自己动手写一把可重入锁https://blo ...
Java之多线程之Lock与Condition -
Lixh1986:
http://win.51apps.com.cn/https: ...
temp -
ztwsl:
不错,支持很好
HttpServletRequest和ServletRequest的区别 -
guodongkai:
谢谢您能将知识精华汇编总结,让初学者们从原理中学会和提高。
javaScript之function定义 -
kangwen23:
谢谢了,顶顶
struts2中的ValueStack学习
一、界面截图:
二、代码:
1、ChatServer.java
2、ServerSideSocket.java
3、ClientSideSocket.java
三、Java Socket通信原理图
四、Java Socket 编程进阶
Will I need a separate socket and thread for every player that joins? [JAVA]
服务器端是否应该为每一个客户端创建一个线程?
I have been learning about sockets for sometime now (I'm quite young) and I think I have a good grip on java sockets. I have decided to create a simple multiplayer Java 2D social game. My goal is to have the server output players' X,Y coordinates and chat every 10 milliseconds. From what I have read, my very average logic tells me that only one user at a time can connect to a socket. So therefore I will need a separate thread and socket for each player that connects.
Is it necessary to have one ServerSocket and thread per player?
Answer:
You should have just one ServerSocket listening on a port that is known to the client. When a client connects to the server, a new Socket object is created and the original ServerSocket goes back to listening again. You should then spin off a new Thread or hand over to an Executor the actual work of talking to the client, otherwise your server will stop listening for client connections.
Here is a very basic sketch of the code you will need.
I have put sockets here since they are easier to get started with, but once you have this working well and want to boost your performance you will probably want to investigate the java.nio.channels package.
There's a good tutorial over at IBM.
-
转载请注明,
原文出处: http://lixh1986.iteye.com/blog/2348001
-
二、代码:
1、ChatServer.java
package com.lixh1986.socket.server; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; import com.lixh1986.socket.model.ServerSideSocket; public class ChatServer { @SuppressWarnings("resource") public static void main(String[] args) { ArrayList<ServerSideSocket> pool = new ArrayList<ServerSideSocket>(); try { ServerSocket serverSocket = new ServerSocket(9999); System.out.println("Server starts up!"); while(true){ /** * ServerSocket.accept(); * Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. A new Socket corresponding to the client socket is created, and this socket will be used for making communication with the client socket. */ ServerSideSocket serverSideSocket = new ServerSideSocket(pool, serverSocket.accept()); Thread t = new Thread(serverSideSocket); System.out.println("socket thread: " + t.getName() + " starts serving."); t.start(); } } catch (IOException e) { e.printStackTrace(); } } }
2、ServerSideSocket.java
package com.lixh1986.socket.model; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; public class ServerSideSocket implements Runnable { private Socket socket; private ArrayList<ServerSideSocket> pool; public ServerSideSocket(ArrayList<ServerSideSocket> pool, Socket socket){ this.pool = pool; this.socket = socket; this.pool.add(this); System.out.println("A client connected!"); } @Override public void run() { receiveMessage(); } /** * read data from ClientSideSocket. */ private void receiveMessage(){ try { byte[] bytes = new byte[1024]; int n = 0; boolean isUserSendQuit = false; while(!isUserSendQuit){ while ( (n = socket.getInputStream().read(bytes)) != -1){ String str = new String (bytes, 0, n); // broadcast this message to other client. for(ServerSideSocket otherSocket : pool){ if(this != otherSocket){ otherSocket.writeMessage(str); } } } } } catch (IOException e1) { System.out.println("receiveMessage:"); System.out.println("A client disconnected!"); }finally{ disconnect(); } } /** * write data to ClientSideSocket. * @param message */ public void writeMessage(String message){ try { socket.getOutputStream().write(message.getBytes()); socket.getOutputStream().flush(); } catch (IOException e1) { System.out.println("writeMessage:"); System.out.println("A client disconnected!"); disconnect(); } } private void disconnect(){ if(pool.remove(this)){ System.out.println("A client is removed successfully!"); System.out.println("pool size: " + pool.size()); }else{ System.out.println("A client is not removed!"); } try { if(socket != null) socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
3、ClientSideSocket.java
package com.lixh1986.socket.client; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; @SuppressWarnings("resource") public class ClientSideSocket { public static void main(String[] args) { try { final Socket socket = new Socket("127.0.0.1", 9999); final Scanner scanner = new Scanner(System.in); System.out.println("I am a client!"); new Thread(new Runnable() { @Override public void run() { try { while(true){ String str = scanner.nextLine(); socket.getOutputStream().write(str.getBytes()); socket.getOutputStream().flush(); } } catch (IOException e) { System.out.println("Writing Quit."); System.exit(0); } } }).start(); new Thread(new Runnable() { @Override public void run() { try { byte[] bytes = new byte[1024]; int n = 0; while(true){ while ( (n = socket.getInputStream().read(bytes)) != -1){ String str = new String (bytes, 0, n); System.out.println(str); } } } catch (IOException e) { System.out.println("Reading Quit."); System.exit(0); } } }).start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
三、Java Socket通信原理图
四、Java Socket 编程进阶
Will I need a separate socket and thread for every player that joins? [JAVA]
服务器端是否应该为每一个客户端创建一个线程?
I have been learning about sockets for sometime now (I'm quite young) and I think I have a good grip on java sockets. I have decided to create a simple multiplayer Java 2D social game. My goal is to have the server output players' X,Y coordinates and chat every 10 milliseconds. From what I have read, my very average logic tells me that only one user at a time can connect to a socket. So therefore I will need a separate thread and socket for each player that connects.
Is it necessary to have one ServerSocket and thread per player?
Answer:
You should have just one ServerSocket listening on a port that is known to the client. When a client connects to the server, a new Socket object is created and the original ServerSocket goes back to listening again. You should then spin off a new Thread or hand over to an Executor the actual work of talking to the client, otherwise your server will stop listening for client connections.
Here is a very basic sketch of the code you will need.
import java.net.*; import java.util.concurrent.*; public class CoordinateServer { public static void main(String... argv) throws Exception { // 'port' is known to the server and the client int port = Integer.valueOf(argv[0]); ServerSocket ss = new ServerSocket(port); // You should decide what the best type of service is here ExecutorService es = Executors.newCachedThreadPool (); // How will you decide to shut the server down? while (true) { // Blocks until a client connects, returns the new socket // to use to talk to the client Socket s = ss.accept (); // CoordinateOutputter is a class that implements Runnable // and sends co-ordinates to a given socket; it's also // responsible for cleaning up the socket and any other // resources when the client leaves es.submit(new CoordinateOutputter(s)); } } }
I have put sockets here since they are easier to get started with, but once you have this working well and want to boost your performance you will probably want to investigate the java.nio.channels package.
There's a good tutorial over at IBM.
-
转载请注明,
原文出处: http://lixh1986.iteye.com/blog/2348001
-
发表评论
-
java 将文件夹所有的文件合并到指定的文件夹下
2020-06-30 19:17 1069场景:将文件夹所有的文件合并到指定的文件夹下 另外:如果想效 ... -
多线程-线程池的四种创建方式
2020-04-01 18:38 489多线程-线程池的四种创建方式 https://blog.cs ... -
Java基础之:nio
2019-11-13 15:38 485一、理论讲解: 史上最强Java NIO入门:担心从入门到放弃 ... -
Java 分布式之:RPC 基本概念
2019-11-13 15:07 464转载: https://www.jianshu.com/p/ ... -
Java之 volatile 关键字原理详解
2019-11-07 15:36 550一、什么是 volatile ? ... -
POI实现excell批注背景图片(仿html浮窗显示图片)
2019-10-21 08:17 693POI实现excell批注背景图片(仿html浮窗显示图片) ... -
Java之设计模式之 Observer 观察者
2019-07-04 17:21 1074观察者设计模式 Java 已经实现了该模式,并且提供了使用类 ... -
HashMap, LinkedHashMap and TreeMap
2019-03-01 11:04 682https://stackoverflow.com/a/177 ... -
Java lib 操作 excel 插入图片
2019-01-19 12:46 881https://poi.apache.org/componen ... -
数据库连接池C3P0
2018-05-29 16:50 898一、名字的由来 很多 ... -
Java8之集合(Collection)遍历 forEach()、stream()
2018-05-29 14:39 20752package java8.collections; ... -
Junit Vs main on "java.util.concurrent.Executors"
2017-11-10 16:44 820Same code with different result ... -
Java之大数据学习路线
2017-11-03 10:08 5722三个月大数据研发学习 ... -
Java中创建对象的5种方式
2017-10-26 14:21 842一、Java之5种创建对象的方式 ————————————— ... -
Log4j和Slf4j的比较
2017-06-23 12:41 1412一直搞不清 Log4j 和 SLF4j 的关系。今天才若有所 ... -
Java之Java7新特性之try资源句式
2017-04-20 14:58 5387Java之Java7新特性之try资源句式 一、【try资源 ... -
Java之 java.util.concurrent 包之ExecutorService之submit () 之 Future
2017-03-04 21:27 3835一、如何使用 ExecutorService.submit() ... -
Java之 java.util.concurrent 包之Executor与ExecutorService
2017-03-04 21:18 2706一、问题: execute() 与 submit() 的区别? ... -
JAVAEE之单用户登录
2017-02-05 11:55 1060单用户登录是系统中数据一直性的解决方案之一。 问题背景: 试 ... -
Java之多线程之线程池之线程重复使用
2017-02-04 13:33 5570一、问题背景 在使用多线程时,如果要开启一个任务,则就需要新 ...
相关推荐
Java Socket网络编程是Java语言中实现网络通信的基础,它提供了低级别的、面向连接的、...而本示例中的简单QQ聊天程序,主要是为了演示Java Socket的基本使用和并发处理,帮助初学者理解网络编程的基本概念和操作流程。
- 为了让用户友好地交互,聊天程序通常会有一个图形用户界面(GUI),可能使用Java的Swing或JavaFX库来实现。用户可以通过GUI输入消息并查看其他人的聊天记录。 通过以上步骤,一个基本的Java聊天室程序就可以构建...
本资源是本人前面发过的一个局域网聊天工具的升级版。...代码保证可用,如有问题请留言,代码较规范,结构清晰,相信对学习java socket编程和swing界面开发的朋友有一定的帮助。 注:main函数在MainFrame类
通过以上步骤,一个简单的Java Socket编程实现的多人聊天室就搭建完成了。这样的系统适合初学者用来学习网络通信的基础知识,包括TCP连接、多线程编程、数据的序列化与反序列化等。通过实际操作,可以帮助理解网络...
总的来说,这个Java的Socket实现的多人聊天程序是一个很好的学习示例,涵盖了网络编程、多线程、并发控制以及用户界面设计等多个方面的知识。通过分析和研究这个项目,开发者可以深入理解Java的Socket通信机制,为...
本资源是本人前面发过的一个局域网聊天工具的升级版。...代码保证可用,如有问题请留言,代码较规范,结构清晰,相信对学习java socket编程和swing界面开发的朋友有一定的帮助。 注:main函数在MainFrame类
6. **输入/输出流**: 在Java的Socket编程中,数据通过输入流和输出流进行读写。ServerSocket和Socket都有相关的输入流和输出流对象,例如InputStream和OutputStream,用于接收和发送数据。 7. **聊天小程序设计**: ...
聊天程序 JavaSocket编程,类似QQ的聊天程序(注册、登陆、聊天等) 1、界面模仿QQ界面,能够发起一对一聊天、接受聊天请求; 2、能够以当前日期和时间(精确到分)命名的文件来保持聊天记录; 3、能够调出聊天记录...
在这个“基于Java Socket编程的局域网聊天程序源代码”项目中,我们可以学习到如何构建一个简单的聊天应用程序,使得在同一局域网内的用户可以相互通信。以下是关于Java Socket编程的一些核心知识点和在该源代码中...
Java Socket实现的简易聊天程序是Java网络编程中的基础应用,主要涉及了客户端(Client)与服务器端(Server)之间的通信。在这个程序中,Socket作为Java提供的API,扮演着连接两端的关键角色,允许双方进行双向数据...
这个简单的聊天程序是一个很好的起点,可以帮助初学者理解Socket编程的基本原理和操作。在深入学习时,还可以探索更多高级特性,如错误处理、心跳机制、加密通信等,以及更复杂的网络应用程序设计。 文件"有关...
在这个“简单聊天程序”中,我们将探讨如何使用Socket来构建一个基本的聊天应用,让两个用户可以通过互联网进行实时交流。 首先,我们需要理解什么是Socket。Socket是网络编程中的一个抽象概念,可以看作是两台...
Java语言中的Socket编程是网络通信的核心技术之一,它允许两个应用程序通过网络进行数据交换。在本教程中,我们将深入探讨如何使用Java实现一个简单的聊天程序,重点在于多线程的应用。 首先,Socket是TCP/IP协议栈...
本文将深入探讨“局域网聊天 socket编程 java源程序”的主题,解析其背后的技术细节和实现原理。 首先,让我们理解“局域网聊天”这个概念。局域网(LAN,Local Area Network)是指在有限地理范围内的计算机网络,...
实现Java Socket聊天多线程编程,图形化界面,多人聊天(群聊),私人聊天,是基于本地模拟的Java聊天程序。 Java Socket聊天程序是我用了三天的时间写出来,用Netbeans建的工程,图形化界面是Netbeans拖拉出来的,...
Java聊天程序是网络编程中的一个经典案例,它利用Socket编程技术实现客户端和服务端之间的通信。在Java中,Socket是TCP/IP协议的应用层接口,用于在两台计算机之间建立可靠的、基于字节流的连接。本项目旨在教授如何...
在这个“java中socket在线编程聊天系统的小案例”中,我们将会探索如何构建一个简单的基于Socket的聊天应用程序。这个案例适用于初学者,可以帮助他们理解Socket编程的基本原理和应用。 首先,Socket在Java中扮演着...
Java版的Socket编程是网络通信的核心技术之一,尤其在构建局域网聊天工具时尤为重要。本项目通过Java实现了一个功能丰富的即时通讯应用,包括全新界面风格、文字聊天、文件传输、窗口抖动以及语音聊天等功能。 1. *...
Java Socket聊天程序是一种基于网络通信的软件应用,它利用了Java的Socket API来实现客户端与服务器之间的实时交互。在这个程序中,"有界面"意味着它不仅包含后台的网络通信逻辑,还具有用户友好的图形用户界面(GUI...
书中提供了多个实用的案例,如简单的聊天室应用、文件传输服务等,这些案例不仅展示了Socket编程的基本原理,也涵盖了多线程、非阻塞I/O和安全通信等高级主题。通过动手实践,读者可以将理论知识转化为实际技能,更...