大饼先生 2006-8-13 15:07
发个最简单却有用的java socket网络编程~
用作学习网络编程之用,程序实现的功能非常简单,即:从客户端传送两个int类型的数到服务端,服务端将两数的结果求和后发送回客户端。下面是客户端程序:
import java.io.*;
import java.net.*;
public class clients{
public static void main(String[] args) throws Exception{
Socket c = new Socket("localhost",1111);
PrintWriter out = new PrintWriter(c.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please input 2 number to request!");
String s1 = in2.readLine();
String s2 = in2.readLine();
out.println(s1);
out.println(s2);
System.out.println(in.readLine());
out.close();
in.close();
c.close();
}
}
服务端程序:
import java.io.*;
import java.net.*;
public class server{
public static void main(String[] args) throws Exception{
ServerSocket serv = new ServerSocket(1111);
Socket c = serv.accept();
PrintWriter out = new PrintWriter(c.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
int x1 = Integer.parseInt(in.readLine());
int x2 = Integer.parseInt(in.readLine());
int x3 = x1+x2;
out.println("answer : "+x3);
in.close();
out.close();
c.close();
serv.close();
}
}
配置好JDK后在命令提示符编译好两个.java的文件生成.class文件,先运行c:\java server,再重新打开一个命令行窗口,运行c:\java clients。可以在clients里看到服务端求出的结果~~
这个小程序只是做为一个初级教学~~实际上socket编程也大概就是在此基础上扩展。比如实现一个自定义协议的C/S程序,可以在客户端将数据包序列化后传送给服务端,服务端依照协议解析数据包,取得相应的数据进行处理后再发回客户端~~
大饼先生 2006-8-15 16:05
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//实现文件下载的小程序
class UIFace extends JFrame{
JTextField url;
public UIFace(){
url = new JTextField(100);
//JTextField fileName = new JTextField()
JLabel j = new JLabel("please input the file's URL you want to download:");
this.add(j,"North");
this.add(url,"South");
url.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try{
InputStream in = new URL(url.getText()).openStream();
String fileName = new String("test."+getName(url.getText()));
FileOutputStream out = new FileOutputStream(fileName);
BufferedOutputStream buf = new BufferedOutputStream(out);
int i;
while ((i=in.read())!=-1){
buf.write(i);
}
in.close();
buf.flush();
out.close();
buf.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
});
}
public static String getName(String url){
//String fileName;
int i = url.trim().length();
String back = url.substring(i-3,i); // 取得文件后缀名
//StringTokenizer st = new StringTokenizer(url);
return back;
}
public static void main(String[] args){
UIFace ui = new UIFace();
ui.setSize(300,70);
ui.setVisible(true);
ui.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
[[i] 本帖最后由 大饼先生 于 2006-8-18 15:28 编辑 [/i]]
大饼先生 2006-8-15 16:06
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Chat extends JFrame {
/**
* 一个简单的基于UDP的聊天程序
*/
private static final long serialVersionUID = 1L;
//private JPanel panel;
private List lst = new List(6);
private JTextField tfIP = new JTextField(10);
private JTextField tfData = new JTextField(20);
private DatagramSocket ds = null;
private JLabel j1 = new JLabel("IP地址:");
private JLabel j2 = new JLabel("想说的话:");
public Chat() {
//super("Chat");
this.add(lst,"Center");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,4));
panel.add(j1);
panel.add(tfIP);
panel.add(j2);
panel.add(tfData);
this.add(panel,"South");
try {
ds = new DatagramSocket(1234);
} catch (SocketException e1) {
e1.printStackTrace();
}
tfData.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try{
byte[] buf = tfData.getText().getBytes();
DatagramPacket p = new DatagramPacket(buf,buf.length,InetAddress.getByName(tfIP.getText().trim()),1234);
ds.send(p); //发送消息
lst.add("localhost to "+tfIP.getText()+" : "+tfData.getText(),0);
}catch(Exception ex){
ex.printStackTrace();
}
tfData.setText("");
}
});
new Thread(new Runnable(){
public void run() {
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf,1024);
while(true)
try {
ds.receive(p);
String s = new String(p.getData(),0,p.getLength());
lst.add(p.getAddress().getHostAddress()+" to localhost : "+s,0);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String[] args){
Chat c = new Chat();
c.setSize(300,400);
c.setVisible(true);
}
}
[[i] 本帖最后由 大饼先生 于 2006-8-18 15:27 编辑 [/i]]
左耳出灵 2006-8-15 22:07
恩 谢谢LZ
往往一个简单明了、有趣的开始是一个初学者的福音
大饼先生 2006-8-18 15:26
下面是一段简单的基于struts MVC开发的应用~~实现将一个特定的文件上传到服务器,经过验证后将文件的数据写入到数据库(验证过程几乎省略了~~为的是方便大家更容易懂些)
下面是JSP页面:[quote]
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<body>
<logic:present name="say_OK"> <!--这里检查request里是否有say_OK的bean-->
Bean say_ok is in exists.
<bean:write name="say_OK"/>
</logic:present>
<html:form action="/ColaAction.do" method="POST" enctype="multipart/form-data">
please select the file that you would like to upload:<br />
<html:file property = "file" /><br />
<html:submit />
</html:form>
</body>
[/quote]
ActionForm:
[quote]
package cola;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import java.util.*;
public final class ColaForm extends ActionForm{
private FormFile file;
public FormFile getFile(){
return this.file;
}
public void setFile(FormFile file){
this.file = file;
}
//public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){}
//简单起见这里并未实现抽象类ActonForm的validate()验证方法~~只是一个简单的bean用来得到来自页面的数据
}[/quote]
Action:
[quote]
package cola;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import java.util.*;
import java.io.*;
public final class ColaAction extends Action{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
ColaForm cf = (ColaForm)form;
FormFile file = cf.getFile();
if (file == null)
{
return mapping.findForward("SUCCESS");
}
String fname = file.getFileName();
String size = Integer.toString(file.getFileSize())+"bytes";
InputStream in = file.getInputStream();
DataFromFileToDB toDB = new DataFromFileToDB(in);
toDB.writeAllToDB();
String s = new String("every this is OK now~!!!");
request.setAttribute("say_OK",s); //将s放到request里
return mapping.findForward("SUCCESS");
}
//其中DataFromFileToDB的writeAllToDB()是一个实现将文件流解析后写入到数据库的方法,数据库连接等操作封装在DataFromFileToDB类里
}[/quote]
struts-config.xml:
[quote]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<!--
This is the Struts configuration file for the "Hello!" sample application
-->
<struts-config>
<!-- ======== Form Bean Definitions =================================== -->
<form-beans>
<form-bean name="ColaForm" type="cola.ColaForm" />
</form-beans>
<action-mappings>
<action path="/ColaAction"
type="cola.ColaAction"
name="ColaForm"
>
<forward name="SUCCESS" path="/cola.jsp" />
</action>
</action-mappings>
<!-- ========== Message Resources Definitions =========================== -->
<message-resources parameter="resources.properties" />
</struts-config>
[/quote]
web.xml:
[quote]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>HelloApp Struts Application</display-name>
<!-- Standard Action Servlet Configuration -->
<servlet>
<servlet-name>action</servlet-name>
<!-- <servlet-class>util.myActionServlet</servlet-class>-->
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</web-app>
[/quote]
大饼先生 2006-8-18 15:53
有兴趣的同学可以下载了去看看~~
把文件夹解压后在WEB-INF下新建一个lib文件夹放入struts的包。再把整个文件夹拷到tomcat目录下的webapps里应该就可以直接通过地址[url]http://localhost/06-08-18/cola.jsp[/url]访问到该应用了~~
我是借地方上传的~~HOHO~~