標籤:tag setname throw java網路編程 port ... span style ram
在java網路編程中,用戶端和伺服器的通訊例子:
先來伺服器監聽的代碼
package com.server;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.net.ServerSocket;import java.net.Socket;import com.jim.Student;public class QQServer { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Start Server..."); QQServer server = new QQServer(); } //建構函式 public QQServer() { Socket s; //建立ServerSocket在9999號連接埠監聽 ServerSocket ss = null; try { ss = new ServerSocket(9999); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("伺服器正在監聽........"); try { System.out.println("開始等待串連..."); s = ss.accept();//阻塞,等待串連 System.out.println("用戶端串連成功"); //接收流 ObjectInputStream ois=new ObjectInputStream(s.getInputStream()); //發送流 ObjectOutputStream oos = new ObjectOutputStream( s.getOutputStream()); //接收Student對象 Student stu = (Student) ois.readObject(); System.out.println(stu.getName()); //發送Student對象 oos.writeObject(new Student("Server")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
用戶端的代碼:
package com.client;import java.io.*;import java.net.*;import com.jim.Student;public class QQClient { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Start QQClient..."); try { QQClient client = new QQClient(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //建構函式 public QQClient() throws IOException { //String address="127.0.0.1"; //int port = 9999 ; try { Socket s = new Socket("127.0.0.1", 9999); Student stu = new Student("Jim"); //發送資訊給伺服器 ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream()); //ObjectInputStream ois=new ObjectInputStream(s.getInputStream()); //接受伺服器傳來的資訊 ObjectInputStream ois=new ObjectInputStream(s.getInputStream()); //發送對象到伺服器 //oos.writeObject(new Student("OKK")); oos.writeObject(stu); //接收伺服器返回的對象 Student re_stu = (Student)ois.readObject(); System.out.println(re_stu.getName()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
在用戶端和服務傳輸的對象對象
package com.jim;public class Student implements java.io.Serializable{ private String name ; private int age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } /** * @param name * 構造方法 */ public Student(String name){ this.name = name; } /** * @param * */ public void study(){ System.out.println(this.name + " is studing"); } }
Java網路編程用戶端和伺服器通訊