小弟在網上搜尋了很多資源,但都很少有sample是教人用socket
在jsp網頁中和java console application 作傳送資料。
經小弟研究一翻後,終於獲得小小成果。
原理:
1. java console application 作為一個 server端,負責接收和即時顯示jsp傳送過來的data。
2. jsp 會使用socket 把 jsp 網頁中的textfield內容即時傳送到 java console application。
result:
java console application :
( 已接收data )
Jsp:
(按go後便會傳送"kelvin"一字)
-------------------------------------------------------------------------
Java console application code ( server )
/**
*
* @author kongyinlam
*/
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class CServer_Recv extends Thread
{
public void run()
{
byte buff[] = new byte[1024];
try
{
ServerSocket svs = new ServerSocket(2526);
SServer_rec.txa1.append("Client connecting for receiving successfully!!\n");
System.out.println("Client connecting for receiving successfully!!");
while(true)
{
Socket s=svs.accept();
InputStream in=s.getInputStream();
int n;
try{
n=in.read(buff);
if(n!=-1){
SServer_rec.txa1.append("Client: "+new String(buff,0,n)+"\n");
System.out.print("Received from client: ");
System.out.print(new String(buff,0,n));
}
}
catch(Exception ee){System.out.println(ee);}
in.close();
s.close();
}
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
}
}
// for GUI
public class SServer_rec
{
static Frame frm=new Frame("JAVA Socket Server AWT Program");
static Button btn1=new Button("Start");
static Button btn2=new Button("Exit");
static Label lab1=new Label("Host IP Address");
static Label title=new Label("JSocket");
static TextArea txa1=new TextArea("",6,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
static TextArea txa2=new TextArea("",6,10,TextArea.SCROLLBARS_NONE);
static TextField txf1=new TextField("127.0.0.1");
// static CServer_send ss=new CServer_send();
static CServer_Recv sr=new CServer_Recv();
public static void main (String[] args)
{
try
{
InetAddress adr=InetAddress.getLocalHost();
txf1.setText(adr.getHostAddress());
btn1.addActionListener(new ActLis());
btn2.addActionListener(new ActLis());
frm.addWindowListener(new WinLis());
frm.setLayout(null);
title.setBounds(20,40,75,40);
btn1.setBounds(280,40,100,20);
btn2.setBounds(280,65,100,20);
frm.setBounds(100,100,400,300);
frm.setBackground(new Color(151,255,255));
lab1.setBounds(100,40,160,20);
txa1.setBounds(20,95,360,140);
txa2.setBounds(20,240,360,40);
txf1.setBounds(100,65,160,20);
txa1.setEditable(false);
title.setFont(new Font("Serief",Font.BOLD+Font.ITALIC,18));
title.setForeground(Color.BLUE);
frm.add(title);
frm.add(btn1);frm.add(btn2);
frm.add(lab1);
frm.add(txa1);frm.add(txa2);
frm.add(txf1);
frm.setVisible(true);
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
}
static class ActLis implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button btn=(Button) e.getSource();
if(btn==btn1)
{
txa1.setText("Waiting for connecting("+txf1.getText()+")...\n");
System.out.println("Waiting for connecting...");
txf1.setEditable(false);
//ss.start();
sr.start();
}
else if(btn==btn2)
System.exit(0);
else
System.out.println("No Button Click!");
}
}
static class WinLis extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
frm.dispose();
System.exit(0);
}
}
}
*
* @author kongyinlam
*/
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class CServer_Recv extends Thread
{
public void run()
{
byte buff[] = new byte[1024];
try
{
ServerSocket svs = new ServerSocket(2526);
SServer_rec.txa1.append("Client connecting for receiving successfully!!\n");
System.out.println("Client connecting for receiving successfully!!");
while(true)
{
Socket s=svs.accept();
InputStream in=s.getInputStream();
int n;
try{
n=in.read(buff);
if(n!=-1){
SServer_rec.txa1.append("Client: "+new String(buff,0,n)+"\n");
System.out.print("Received from client: ");
System.out.print(new String(buff,0,n));
}
}
catch(Exception ee){System.out.println(ee);}
in.close();
s.close();
}
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
}
}
// for GUI
public class SServer_rec
{
static Frame frm=new Frame("JAVA Socket Server AWT Program");
static Button btn1=new Button("Start");
static Button btn2=new Button("Exit");
static Label lab1=new Label("Host IP Address");
static Label title=new Label("JSocket");
static TextArea txa1=new TextArea("",6,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
static TextArea txa2=new TextArea("",6,10,TextArea.SCROLLBARS_NONE);
static TextField txf1=new TextField("127.0.0.1");
// static CServer_send ss=new CServer_send();
static CServer_Recv sr=new CServer_Recv();
public static void main (String[] args)
{
try
{
InetAddress adr=InetAddress.getLocalHost();
txf1.setText(adr.getHostAddress());
btn1.addActionListener(new ActLis());
btn2.addActionListener(new ActLis());
frm.addWindowListener(new WinLis());
frm.setLayout(null);
title.setBounds(20,40,75,40);
btn1.setBounds(280,40,100,20);
btn2.setBounds(280,65,100,20);
frm.setBounds(100,100,400,300);
frm.setBackground(new Color(151,255,255));
lab1.setBounds(100,40,160,20);
txa1.setBounds(20,95,360,140);
txa2.setBounds(20,240,360,40);
txf1.setBounds(100,65,160,20);
txa1.setEditable(false);
title.setFont(new Font("Serief",Font.BOLD+Font.ITALIC,18));
title.setForeground(Color.BLUE);
frm.add(title);
frm.add(btn1);frm.add(btn2);
frm.add(lab1);
frm.add(txa1);frm.add(txa2);
frm.add(txf1);
frm.setVisible(true);
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
}
static class ActLis implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button btn=(Button) e.getSource();
if(btn==btn1)
{
txa1.setText("Waiting for connecting("+txf1.getText()+")...\n");
System.out.println("Waiting for connecting...");
txf1.setEditable(false);
//ss.start();
sr.start();
}
else if(btn==btn2)
System.exit(0);
else
System.out.println("No Button Click!");
}
}
static class WinLis extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
frm.dispose();
System.exit(0);
}
}
}
Jsp code ( client )
* 2個jsp file, 1 for 界面, 另一個for socket
1. index.jsp
<%--
Document : main
Created on : 2015/4/8, 下午 07:25:28
Author : Kong Yin Lam
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form type="post" action="SocketClientSend.jsp">
<input name="text"></input>
<input type="submit" value="go"></input>
</form>
<h1>Hello World!</h1>
</body>
</html>
Document : main
Created on : 2015/4/8, 下午 07:25:28
Author : Kong Yin Lam
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form type="post" action="SocketClientSend.jsp">
<input name="text"></input>
<input type="submit" value="go"></input>
</form>
<h1>Hello World!</h1>
</body>
</html>
2. SocketClientSend.jsp // for socket transfer data
<%--
Document : index
Created on : 2015/4/8, 下午 06:04:02
Author : Kong Yin Lam
--%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.net.Socket"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<H1>Creating Client/Server Applications</H1>
<%
try{
Socket s=new Socket("192.168.0.102", 2526); // your ip, up to u
System.out.println("Connected with server for sending successfully!!");
System.out.println("Data transfering...");
String str=request.getParameter("text"); // 取得index.jsp中的textfield內容
OutputStream outed=s.getOutputStream();
System.out.println("keeping connection!");
outed.write(str.getBytes());
System.out.println("Send:"+str);
System.out.println("You: send");
}
catch(java.net.ConnectException e){}
%>
<% response.sendRedirect("index.jsp"); // back to index.jsp%>
</body>
</html>