Java Socket 连接 Client端 和 Server端
Client端:
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ChatClient {
private static final String SERVER_IP = "127.0.0.1";
private static final int SERVER_PORT = 8888;
Socket socket = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
private static Scanner in = new Scanner(System.in);
private static String hostInfo = null;
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launch();
}
public void launch() {
connect();
tRecv.start();
}
public void connect() {
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
bConnected = true;
InetAddress addr = InetAddress.getLocalHost();
String ip = addr.getHostAddress().toString();// 获得本机IP
String address = addr.getHostName().toString();// 获得本机名称
hostInfo = ip + "\t" + address + "\tconnected.";
System.out.println(hostInfo);
dos.writeUTF(hostInfo);
dos.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() throws IOException {
try {
dos.close();
dis.close();
socket.close();
} catch (IOException e) {
}
}
private class RecvThread implements Runnable {
public void run() {
while (bConnected) {
try {
if (in.hasNext()) {
String talk = in.nextLine();
if (talk.equals("quit")) {
disconnect();
bConnected = false;
break;
}
dos.writeUTF(talk);
dos.flush();
}
String talk = dis.readUTF();
System.out.println(talk);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
server端:
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.err.println("port in use.please stop program using this port and restart.");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
// System.out.println("a client connected.");
new Thread(c).start();
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e) {
clients.remove(this);
System.out.println("a client quit.");
//e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
solveTalk(str);
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private void solveTalk(String talk) {
System.out.println(talk);
for(int i=0;i<clients.size();i++) {
Client c = clients.get(i);
c.send(talk);
}
}
}
}
Java Socket 连接 Client端 和 Server端的更多相关文章
- 多个client与一个server端通信的问题
多个client与一个server端通信的问题 上篇博文主要是讲的关于client与server端的通信问题.在上篇博文中当我们仅仅有一个client訪问我们的server时是能够正常执行的,可是当我 ...
- Fms3中client端与server端交互方式汇总
系列文章导航 Flex,Fms3相关文章索引 Flex和Fms3打造在线聊天室(利用NetConnection对象和SharedObject对象) Fms3和Flex打造在线视频录制和回放 Fms3和 ...
- java Socket通信,客户端与服务端相互发消息
1.通信过程 网络分为应用层,http.ssh.telnet就是属于这一类,建立在传输层的基础上.其实就是定义了各自的编码解码格式,分层如下: 2.Socket连接 上述通信都要先在传输层有建立连接的 ...
- 从零开始学习Node.js例子四 多页面实现数学运算 续二(client端和server端)
1.server端 支持数学运算的服务器,服务器的返回结果用json对象表示. math-server.js //通过监听3000端口使其作为Math Wizard的后台程序 var math = r ...
- JAVA Socket连接服务器时可能抛出的异常
1.UnknownHostException:host(非ip)无法识,就会报该异常,www.google.com.hk这个虽然也ping不通,但是不会报该错,因为他是一个确实存在的域名.他会报Con ...
- java虚拟机--jvm client模式与server模式的区别
JVM Server模式与client模式启动,最主要的差别在于:-Server模式启动时,速度较慢,但是一旦运行起来后,性能将会有很大的提升.JVM如果不显式指定是-Server模式还是-clien ...
- Java HotSpot(TM) Client VM 与 server VM 的配置
在Linux 6.5 下安装Elasticsearch 出现错误: JVM is using the client VM [Java HotSpot(TM) Client VM] but should ...
- oracle client 低于 oracle server 端,导致报错ORA-01882
https://forums.toadworld.com/t/ora-01882-when-i-want-to-view-records-con-dba-scheduler-jobs-toad-10- ...
- Dart Socket 与Java Socket连接
------------------------------------------------------------- Dart SocketClient----------------- ...
随机推荐
- IIS application pool access desktop denied
https://stackoverflow.com/questions/5437723/iis-apppoolidentity-and-file-system-write-access-permiss ...
- AutoIT: 学习对GUI Sample上所有的资源进行操作
$handle= WinGetHandle("Sample GUI") ;,"SRE Example 3 Result", $handle) $ctrl= Co ...
- AutoIT: WinSetState可以定义窗口大小
Example() FuncExample() ; Run Notepad Run("notepad.exe") ; Wait seconds for the Notepad wi ...
- 循环冗余检验 (CRC) 算法原理
Cyclic Redundancy Check循环冗余检验,是基于数据计算一组效验码,用于核对数据传输过程中是否被更改或传输错误. 算法原理 假设数据传输过程中需要发送15位的二进制信息g=10100 ...
- linux上部署javaWeb项目
将web项目打成war包,上传到Linux操作系统tomcat安装目录下的webapps下即可!
- nginx静态资源服务器简单配置
有时候我们可以把服务器的一些文件放在固定目录以便下载,比如image,css,js等.就可以使用nginx转发静态资源. 参考链接:https://blog.csdn.net/name_is_wl/a ...
- Python中处理日期时间库的使用方法(转载)
<本文来自公众号“大邓带你玩python”,转载> 用百分之20时间,学会解决百分之80的问题. 常用的库有time.datetime.其中datetime库是对time库的封装,所以使用 ...
- 【洛谷3822】[NOI2017] 整数(线段树压位)
题目: 洛谷 3822 分析: 直接按题意模拟,完了. 将每次加 / 减拆成不超过 \(32\) 个对单独一位的加 / 减. 考虑给一个二进制位(下称「当前位」)加 \(1\) 时,如果这一位本来就是 ...
- XmlPullParser接口详述
带*的是非常重要的函数.点击有说明.setInputgetDepthisWhitespacegetTextisEmptyElementTaggetAttributeCountgetAttributeV ...
- this关键字的构造方法的使用
package com.wh.Object3; public class this_Demo { private String name; private double price; private ...