可以在tomcat环境下用Java程序实现socket通信,代码如下:
服务端:
/**
*
*/
package com.dnion.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
***************************************************************
* 项目名称:JavaThread
* 程序名称:JabberServer
* 日期:2015-7-11 下午21:01:12
* 作者:Administrator
* @version
***************************************************************
*/
public class JabberServer {
public static int PORT = 8080;
public static void main(String[] agrs) {
ServerSocket s = null;
Socket socket = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
//设定服务端的端口号
s = new ServerSocket(PORT);
System.out.println("ServerSocket Start:"+s);
//等待请求,此方法会一直阻塞,直到获得请求才往下走
socket = s.accept();
System.out.println("Connection accept socket:"+socket);
//用于接收客户端发来的请求
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//用于发送返回信息,可以不需要装饰这么多io流使用缓冲流时发送数据要注意调用.flush()方法
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
while(true){
String str = br.readLine();
if(str.equals("END")){
break;
}
System.out.println("Client Socket Message:"+str);
Thread.sleep(1000);
pw.println("Message Received");
pw.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println("Close.....");
try {
br.close();
pw.close();
socket.close();
s.close();
} catch (Exception e2) {
}
}
}
}
客户端:
/**
*
*/
package com.dnion.socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
/**
***************************************************************
* 项目名称:JavaThread 程序名称:JabberClient
* 作者:Administrator
* @version
***************************************************************
*/
public class JabberClient {
/**
* 方法名:main
*
* @param @param args
* @return void
*/
public static void main(String[] args) {
Socket socket = null;
BufferedReader br = null;
PrintWriter pw = null;
try {
//客户端socket指定服务器的地址和端口号
socket = new Socket("127.0.0.1", JabberServer.PORT);
System.out.println("Socket=" + socket);
//同服务器原理一样
br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())));
for (int i = 0; i < 10; i++) {
pw.println("howdy " + i);
pw.flush();
String str = br.readLine();
System.out.println(str);
}
pw.println("END");
pw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
System.out.println("close......");
br.close();
pw.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
用mina吧,轻量级的框架,基于java nio,直接发包的,自己可以写发送数据的编解码,扩展性强。如果是tomcat的话,服务器通信直接采用http协议,利用url请求比较靠谱。
java的话就用 mina 吧,apache的开源