按照java开发技术大全(刘新-清华出版社)的指导,今天尝试了一下java的网络作用
一下代码采用 的是tcp/ip连接方式,代码不是很难
服务器端代码:
- package com.mutouyihao;
- import java.net.ServerSocket;
- import java.net.Socket;
- //server文件
- public class server
- {
- public static void main(String[] args){
- try{
- System.out.println("等待连接");
- ServerSocket sk = new ServerSocket(4000);
- Socket connectToClient = null;
- while(true){
- connectToClient=sk.accept();
- System.out.println(connectToClient.getInetAddress()+"建立连接");
- new ServerThread(connectToClient);
- }
- }catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- package com.mutouyihao;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.Socket;
- //供server调用
- public class ServerThread extends Thread
- {
- private Socket connectToClient;
- private DataInputStream inFromClient;
- private DataOutputStream outToClient;
- public ServerThread(Socket soc) throws IOException
- {
- super();
- connectToClient = soc;
- inFromClient = new DataInputStream(connectToClient.getInputStream());
- outToClient = new DataOutputStream(connectToClient.getOutputStream());
- start();
- }
- public void run()
- {
- try
- {
- String str;
- boolean goon = true;
- while (goon)
- {
- str = inFromClient.readUTF();
- if ( !str.equals("bye") )
- {
- str = "return string" + str;
- outToClient.writeUTF(str);
- outToClient.flush();
- }
- else
- {
- goon = false;
- outToClient.writeUTF("bye");
- outToClient.flush();
- }
- }
- inFromClient.close();
- outToClient.close();
- connectToClient.close();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
client代码
- package com.mutouyihao;
- import java.io.BufferedReader;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.InputStreamReader;
- import java.net.Socket;
- public class Client
- {
- public static void main(String[] args)
- {
- try
- {
- Socket connectionToServer = new Socket("localhost", 4000);
- DataInputStream inFromServer = new DataInputStream(connectionToServer.getInputStream());
- DataOutputStream outToServer = new DataOutputStream(connectionToServer.getOutputStream());
- System.out.println("input your number now:");
- String outStr, inStr;
- boolean goon = true;
- BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
- while (goon)
- {
- outStr = buf.readLine();
- outToServer.writeUTF(outStr);
- outToServer.flush();
- inStr = inFromServer.readUTF();
- if ( !inStr.equals("bye") )
- System.out.println("the returned data is:"+inStr);
- else
- goon = false;
- }
- inFromServer.close();
- outToServer.close();
- connectionToServer.close();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }