更新:这个项目已经不做了,不过TCP/IP的通信之后被用在了数字图像处理的项目上,还是很有用的。
最终版本:
svergui.java
import java.net.*;
import java.io.*;
import java.util.*;
public class svergui {
private static ServerSocket SSocket;
private static int port;
//private static int port=10021;
private Hashtable ht = new Hashtable();
Socket socket;
public svergui() throws IOException {
try{
SSocket=new ServerSocket(port);
System.out.println("Server is crerted and wating Client to connect...");
while (true){
socket=SSocket.accept();
System.out.println("Client IP="+socket.getInetAddress().getHostAddress());
DataOutputStream outstream = new DataOutputStream(socket.getOutputStream());
ht.put(socket,outstream);
Thread thread = new Thread(new ServerThread(socket,ht));
thread.start();
}
}catch(IOException ex){
ex.printStackTrace();
}
}
public static void main(String args[]) throws Exception{
if(args.length<1){
System.out.println("Usage:java svergui[port]");
System.exit(1);
}
port=Integer.parseInt(args[0]);
//port=10012;
svergui ServerStart = new svergui();
}
}
class ServerThread extends Thread implements Runnable{
private Socket socket;
private Hashtable ht;
public ServerThread(Socket socket,Hashtable ht){
this.socket =socket;
this.ht =ht;
}
public void run(){
DataInputStream instream;
try{
instream = new DataInputStream(socket.getInputStream());
while(true){
String message = instream.readUTF();
System.out.println("message:"+message);
synchronized(ht){
for (Enumeration e =ht.elements();e.hasMoreElements();){
DataOutputStream outstream=(DataOutputStream)e.nextElement();
try{
outstream.writeUTF(message);
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
}catch(IOException ex){
}
finally{
synchronized(ht){
System.out.println("Remove connection:"+socket);
ht.remove(socket);
try{
socket.close();
}catch(IOException ex){
}
}
}
}
}
usergui.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
class usergui extends Frame implements ActionListener,Runnable{
TalkRoom TalkWork = new TalkRoom();
TextField TalkInput = new TextField();
Socket socket;
static String iaddr;
static int port;
static String user;
DataOutputStream outstream;
DataInputStream instream;
public usergui(){
super("Client");
try{
socket = new Socket(InetAddress.getByName(iaddr),port);
outstream = new DataOutputStream(socket.getOutputStream());
instream = new DataInputStream(socket.getInputStream());
add(TalkWork,BorderLayout.CENTER);
add(TalkInput,BorderLayout.SOUTH);
TalkInput.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
System.exit(0);
}
});
setSize(500,350);
setVisible(true);
new Thread(this).start();
}catch(Exception e){
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent evt){
if(evt.getSource()==TalkInput){
try{
outstream.writeUTF(user+">"+TalkInput.getText());
TalkWork.PrintTalk(TalkInput.getText(),Color.red);
}catch(Exception e){
System.out.println(e.getMessage());
}
TalkInput.setText(null);
}
}
public void run(){
try{
while(true){
String NetTransferLine = instream.readUTF();
TalkWork.PrintTalk(NetTransferLine,Color.black);
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String args[]){
if(args.length<3){
System.out.println("USAGE:java usergui [iaddr][port][user]");
System.exit(1);
}
iaddr=args[0];
port=Integer.parseInt(args[1]);
user=args[2];
usergui ClientStart=new usergui();
}
}
class TalkRoom extends Component{
Vector PastLine = new Vector();
Vector NewLine = new Vector();
synchronized void PrintTalk(String s,Color c){
NewLine.addElement(new SaveLine(s,c));
repaint();
}
public void paint(Graphics g){
synchronized(this){
while(NewLine.size()>0){
PastLine.addElement(NewLine.elementAt(0));
NewLine.removeElementAt(0);
}
while(PastLine.size()>40){
PastLine.removeElementAt(0);
}
}
FontMetrics fontM = g.getFontMetrics();
int margin =fontM.getHeight()/2;
int w =getSize().width;
int y =getSize().height-fontM.getHeight()-margin;
for(int i =PastLine.size()-1;i>=0;i--){
SaveLine ShowLine =(SaveLine)PastLine.elementAt(i);
g.setColor(ShowLine.clr);
g.setFont(new Font(ShowLine.str,Font.BOLD,12));
g.drawString(ShowLine.str,margin,y+fontM.getAscent());
y-=fontM.getHeight();
}
}
}
class SaveLine{
String str;
Color clr;
SaveLine(String str,Color clr){
this.str=str;
this.clr=clr;
}
}
==============
通信网基础的课程三级项目,刚拿到的时候是一脸懵逼的,但是上网查了一下,其实java 的socket类实现服务器端的设计还蛮简单的。
这次首先利用例程编译一下。
结果如下:
源代码如下:
server.java(然而其实是客户端,之后再改改)
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class server {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws IOException {
Socket s=new Socket("10.52.25.31",10002);
OutputStream out=s.getOutputStream();
out.write("这是来自客户端的消息".getBytes());
InputStream is=s.getInputStream();
byte buf[]=new byte[1024];
int len=is.read(buf);
System.out.println(new String(buf,0,len));
s.close();
}
SocketDemo.java(服务器端)
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10002);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "....connected....");
InputStream in = s.getInputStream();
int len = 0;
byte[] buf = new byte[1024];
len = in.read(buf);
System.out.println(new String(buf, 0, len));
OutputStream os=s.getOutputStream();
os.write("这是来自服务器端的消息".getBytes());
os.close();
s.close();
ss.close();
}
}
java的编译与运行。
java使用自带的javac编译器进行编译,因为程序中有中文的情况,国际版的javac会出问题。
必须使用javac -encoding UTF-8 文件名
进行编译,才不会报错。
运行也有个坑,如果执行
java 编译好的class文件.class
会找不到class文件,只能直接运行
java class文件名不带扩展名
才能正确执行。
之后要做的事todo list:
1.将客户端,服务器端改名
2.改成可多次收发信息的形态
3.能够收发自己填入的信息
4.安卓端编程。
5.反推送自己填入的信息,编程可以聊天的状态。
6.多客户端接入。
预计在第三周之前完成。