本文主要讲解java socket服务端通信内容,服务端监听客户端,并且获取客户端的消息。
监听的主要代码是一个while死循环,因为需要实现持续监听。读者可重点阅读MySocketServer
类的代码。详细代码如下:
package com.test;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MySocketServer {
private int port;
ServerSocket soc = null;
Socket client = null;
public MySocketServer(int port){
super();
try {
soc = new ServerSocket(port);
//soc.setSoTimeout(10000);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
//给客户端发送消息
public void sendDataToClient(String msg){
if (client == null){
System.out.println("当前无客户端连接");
return;
}
try {
OutputStream out = client.getOutputStream();
out.write(msg.getBytes());
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public void recDataFromClient(){
while (true){
try {
if ( (client = soc.accept()) != null ) {
recDataFromClient(client);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
public void recDataFromClient(Socket AClient){
byte[] b=null;
StringBuilder rec = null;
try {
String ip= "来自主机"+AClient.getRemoteSocketAddress() + "的消息:";
InputStream in = AClient.getInputStream();
b = new byte[1024];
int len= 0 ;
while ( (len=in.read(b))!=-1){
String strText= new String(b,0,len);
writeDataToTxt(strText);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public void writeDataToTxt(String strText){
String fileName = "msg.txt";
File f = new File(fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(f,f.exists());
if (f.exists()){
strText = "\n" + strText;
}
out.write(strText.getBytes());
out.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
out.close();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
}
package com.test;
import java.util.Scanner;
public class ServerSocketDemo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int port = 8080;
MySocketServer server = new MySocketServer(port);
System.out.println("Socket服务端已启动,端口号是:"+port);
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
// TODO 自动生成的方法存根
server.recDataFromClient();
}
});
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
// TODO 自动生成的方法存根
while (true){
Scanner sc= new Scanner(System.in);
String st = sc.nextLine();//获取输入信息
server.sendDataToClient(st);
}
}
});
t1.start(); //接收客户端的消息
t2.start(); //给客户端发送消息
}
}