模拟多客户端进行TCP连接[Java]
程序员文章站
2024-03-23 09:35:58
...
TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议。
*服务端不断接收来自客户端的请求*Server.java
package com.example.tang.tcp;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class Server {
ServerSocket ss;
public Server() {
try {
ss=new ServerSocket(9999);//创建ServerSocket对象,端口9999
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new myThread(ss).start();//启动接收消息线程
}
public static void main(String[] args){
new Server();
}
class myThread extends Thread{
ServerSocket ss;
InputStream is;
DataInputStream br;
Socket socket;
public myThread(ServerSocket ss){//将ServerSocket连接信息传入
this.ss=ss;
}
@Override
public void run() {
super.run();
byte b[]=new byte[1024];
int flag=0;
while(true){
try {
socket=ss.accept();//接收客户端连接的socket
is= socket.getInputStream();
br=new DataInputStream(is);
String receive=br.readUTF();
System.out.println(receive);
//回送给客户端消息
OutputStream os=socket.getOutputStream();
DataOutputStream dop=new DataOutputStream(os);
dop.writeUTF("我收到了第"+flag+"客户端");
flag++;
} catch (SocketException e) {
continue;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
*模拟多个客户端发送一次即时消息*Client.java
package com.example.tang.tcp;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
Socket socket;
public Client() {
try {
socket=new Socket("127.0.0.1", 9999);//连接9999端口,主机127.0.0.1
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//for(int i=0;i<5;i++){
sendMsg("我是客户端", socket);
receiveMsg(socket);
//}
}
public static void main(String[] args) throws IOException {
for(int i=0;i<5;i++)//模拟四个即时客户端
new Client();
}
public void sendMsg(String msg,Socket socket){//发送消息
try {
OutputStream os = socket.getOutputStream();
DataOutputStream dop=new DataOutputStream(os);
dop.writeUTF(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receiveMsg(Socket socket){//接收消息
try {
InputStream is=socket.getInputStream();
DataInputStream br=new DataInputStream(is);
String location=br.readUTF();
System.out.println(location);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上仅供学习交流,有错之处还望指出。新浪微博:唐智勤Wz。个人邮箱:[email protected]
上一篇: 7. Python之元组&字典&集合
下一篇: 7. go 集合map