一个最简单的通话程序 通话器服务器:
import java.net.*;
import java.io.*;
import java.lang.*; public class myserver{
public static void main(String args[]){
ServerSocket server;
Socket socket;
String s;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS; try{
//在端口4321注册服务
server=new ServerSocket(4321);
socket=server.accept();//监听窗口,等待连接 System.out.println("server ok");
System.out.println("************************************************");
System.out.println(""); //获得对应Socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in);
while(true){
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");
s=DIS.readLine(); //读入从client传来的字符串
System.out.println("client said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
System.out.print("you say:");
s=in.readLine(); //读取用户输入的字符串
PS.println(s); //将读取得字符串传给client
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 } //关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭sockey
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
通话器客户端
import java.net.*;
import java.io.*;
import java.lang.*; public class myclient{
public static void main(String args[]){
if (args.length<1){ //判断命令加参数没有
System.out.println("you forget the name of the server!");
System.out.println("see also: myclient yxf");
System.exit(1); //如果没加参数就退出
} Socket socket;
String s="[email protected]";
String len;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try{
//向主机名为args[0]的服务器申请连接
//注意端口号要与服务器保持一致:4321
socket=new Socket(args[0],4321); System.out.println("client ok");
System.out.println("************************************************");
System.out.println(""); //获得对应socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in); while(true){
System.out.print("you say:");
s=in.readLine(); //读取用户输入的字符串
PS.println(s); //将读取得字符串传给server
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
else
{
System.out.println("");
System.out.println("please wait server's message...");
System.out.println("");
}
s=DIS.readLine(); //从服务器获得字符串
System.out.println("server said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 } //关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭socket
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
import java.net.*;
import java.io.*;
import java.lang.*; public class myserver{
public static void main(String args[]){
ServerSocket server;
Socket socket;
String s;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS; try{
//在端口4321注册服务
server=new ServerSocket(4321);
socket=server.accept();//监听窗口,等待连接 System.out.println("server ok");
System.out.println("************************************************");
System.out.println(""); //获得对应Socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in);
while(true){
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");
s=DIS.readLine(); //读入从client传来的字符串
System.out.println("client said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
System.out.print("you say:");
s=in.readLine(); //读取用户输入的字符串
PS.println(s); //将读取得字符串传给client
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 } //关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭sockey
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
通话器客户端
import java.net.*;
import java.io.*;
import java.lang.*; public class myclient{
public static void main(String args[]){
if (args.length<1){ //判断命令加参数没有
System.out.println("you forget the name of the server!");
System.out.println("see also: myclient yxf");
System.exit(1); //如果没加参数就退出
} Socket socket;
String s="[email protected]";
String len;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try{
//向主机名为args[0]的服务器申请连接
//注意端口号要与服务器保持一致:4321
socket=new Socket(args[0],4321); System.out.println("client ok");
System.out.println("************************************************");
System.out.println(""); //获得对应socket的输入/输出流
Is=socket.getInputStream();
Os=socket.getOutputStream();
//建立数据流
DIS=new DataInputStream(Is);
PS=new PrintStream(Os);
DataInputStream in=new DataInputStream(System.in); while(true){
System.out.print("you say:");
s=in.readLine(); //读取用户输入的字符串
PS.println(s); //将读取得字符串传给server
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出
else
{
System.out.println("");
System.out.println("please wait server's message...");
System.out.println("");
}
s=DIS.readLine(); //从服务器获得字符串
System.out.println("server said:"+s); //打印字符串
if(s.trim().equals("BYE"))break; //如果是"BYE",就退出 } //关闭连接
DIS.close(); //关闭数据输入流
PS.close(); //关闭数据输出流
Is.close(); //关闭输入流
Os.close(); //关闭输出流
socket.close(); //关闭socket
}
catch(Exception e){
System.out.println("Error:"+e);
}
}
}
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;public class Info extends HttpServlet {
ServletConfig config; public void init(ServletConfig tconfig) throws ServletException {
super.init(tconfig);
config=tconfig;} public String getServletInfo() {
return "Info version 1.9: a demo and diagnostic servlet from vqSoft";} private void pp(PrintWriter os, String name, String value) {
os.print("<b>"+name+": </b>");
if (value==null)
os.print("<b>none</b>");
else
os.print(value);
os.println("<br>");}
private void pp(PrintWriter os, String name, int value) {
pp(os, name, String.valueOf(value));} public void dostuff(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException {
log("invoked");
rep.setContentType("text/html");
PrintWriter os=rep.getWriter();
os.println("<html>");
os.println("<head><title>Info servlet</title></head>");
os.println("<body bgcolor=#add8af>");
os.println("<table border=0 cellspacing=0 cellpadding=2 cols=3 width=100%>");
os.println("<tr><td valign=top>");
os.println("<h1 align=center>Info servlet</h1>");
os.println("<hr>");
os.println("<p>This page was generated by <i>Info</i> version 1.9, a demo and diagnostic servlet supplied with <a href=http://www/vqsoft.com/vq/server/index.html><i>vq</i>Server</a>. ");
os.println("<i>Info</i> lists its initialisation parameters, information about the http request which invoked it and the http request parameters passed to it.</p>");
os.println("<hr>");
os.println("<h3>Servlet initialisation parameters</h3>");
Enumeration e=config.getInitParameterNames();
if (!e.hasMoreElements())
os.println("<b>None!</b>");
else while (e.hasMoreElements()) {
String name=(String) e.nextElement();
String value=config.getInitParameter(name);
pp(os, name, value);}
os.println("<hr>");
os.println("<h3>Request parameters</h3>");
pp(os, "Request method", req.getMethod());
pp(os, "Request URI", req.getRequestURI());
pp(os, "Request protocol", req.getProtocol());
pp(os, "Servlet path", req.getServletPath());
pp(os, "Path info", req.getPathInfo());
pp(os, "Path translated", req.getPathTranslated());
pp(os, "Query string", req.getQueryString());
pp(os, "Content length", req.getContentLength());
pp(os, "Content type", req.getContentType());
pp(os, "Server name", req.getServerName());
pp(os, "Server port", req.getServerPort());
pp(os, "Remote user", req.getRemoteUser());
pp(os, "Remote address", req.getRemoteAddr());
pp(os, "Remote host", req.getRemoteHost());
pp(os, "Authorization scheme", req.getAuthType());
os.println("<hr>");
os.println("<h3>Request headers</h3>");
e=req.getHeaderNames();
if (!e.hasMoreElements())
os.println("<b>None!</b>");
else while (e.hasMoreElements()) {
String name=(String) e.nextElement();
String value=(String) req.getHeader(name);
pp(os, name, value);}
os.println("<hr>");
os.println("<h3>Servlet parameters</h3>");
e=req.getParameterNames();
if (!e.hasMoreElements())
os.println("<b>None!</b>");
else while (e.hasMoreElements()) {
String name=(String) e.nextElement();
String value=req.getParameter(name);
StringBuffer tbuffer=new StringBuffer();
pp(os, name, value);}
os.println("<hr>");
os.println("<h3>Other servlets (by name)</h3>");
ServletContext tcontext=config.getServletContext();
e=tcontext.getServletNames();
if (!e.hasMoreElements())
os.println("<b>None!</b>");
else while (e.hasMoreElements()) {
os.println((String) e.nextElement()+"<br>");}
os.println("<hr>");
os.println("<h3>Other servlets</h3>");
e=tcontext.getServlets();
if (!e.hasMoreElements())
os.println("<b>None!</b>");
else while (e.hasMoreElements()) {
Servlet tservlet=(Servlet) e.nextElement();
os.println(tservlet.getServletInfo()+"<br>");}
os.println("<hr>");
os.println("<p><i>Info</i> version 1.9. <i>Info</i> and <a href=http://www/vqsoft.com/vq/server/index.html><i>vq</i>Server</a> are copyright © 1997-99 Steve Shering and <i>vq</i>Soft.");
os.println("</td>");
os.println("<td width=20></td>");
os.println("<td valign=top width=150>");
os.println("<a href=/index.html><img src=/vq/server/icons/utab.gif border=0 height=15 width=15>Home page</A>");
os.println("</td>");
os.println("</table>");
os.println("</body></html>");
os.flush();} public void doGet(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException {
dostuff(req, rep);} public void doPost(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException {
dostuff(req, rep);}}---------------
[email protected]
dylanwolf() 的代码是通过socket建立client与server的通话。
路人甲的代码是从servlet输出一个html。其实你这个问题可以参看一下《java网络编程》一书,上面的详细说明。主的的方法就是URLConnection和URL这两个类的应用。我帖一段代码,就是书上的例子,你看一下吧,或是去书店直接看一下这本书,orilly出的那本书。import java.net.*;
import java.io.*;public class SourceViewer2 { public static void main (String[] args) { if (args.length > 0) {
try {
//Open the URLConnection for reading
URL u = new URL(args[0]);
URLConnection uc = u.openConnection();
InputStream raw = uc.getInputStream();
InputStream buffer = new BufferedInputStream(raw);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(buffer);
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException e) {
System.err.println(args[0] + " is not a parseable URL");
}
catch (IOException e) {
System.err.println(e);
} } // end if } // end main} // end SourceViewer2还有一个是这样写的:import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;public class SourceViewer3 { public static void main (String[] args) { for (int i = 0; i < args.length; i++) {
try {
//Open the URLConnection for reading
URL u = new URL(args[i]);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
int code = uc.getResponseCode();
String response = uc.getResponseMessage();
System.out.println("HTTP/1.x " + code + " " + response);
for (int j = 1; ; j++) {
String header = uc.getHeaderField(j);
String key = uc.getHeaderFieldKey(j);
if (header == null || key == null) break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
} // end for
InputStream in = new BufferedInputStream(uc.getInputStream());
// chain the InputStream to a Reader
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException e) {
System.err.println(args[0] + " is not a parseable URL");
}
catch (IOException e) {
e.printStackTrace();
System.err.println(e);
} } // end if } // end main} // end SourceViewer2
对了,to 路人甲: 你的程序现在运行不了,我给你发了mail希望能尽快回复。不好意思。我对java是初学者。
to sharetop: 你的程序SourceViewer3 很好,但是没有request header的信息,知道怎么加上么?