Java Socket Programming __ios

Source: Internet
Author: User
Tags gettext stub

Socket programming is through the socket class to write the network communication program, for the network communication program, divided into two, one is the server program, one is the client program. The server program creates a ServerSocket object (a server socket) that accepts a connection request from the client by calling the Accept () method, and the client program creates a socket object to connect to the server, and the connection request succeeds The server also creates a new socket to connect with the client, and the server continues to wait for the new request.


first, the client sends a message to the server Server side:


Import java.net.*;
Import java.io.*;

public class Server {

	datainputstream din;
	DataOutputStream dout;
	ServerSocket SS;
	Socket SC;
	
	Public Server () {
		try {
			ss = new ServerSocket (9999);//create server socket
			sc = ss.accept ();/wait for connection request from client
			DIN = New DataInputStream (Sc.getinputstream ()); Get data input stream
			String msg = Din.readutf ();
			SYSTEM.OUT.PRINTLN ("Client said:" + msg);
			Din.close ();
			Sc.close ();
		} catch (Exception e) {
			e.printstacktrace ();
		}
	}
	public static void Main (string[] args) {
		new Server ();
	}
}


In the above server-side code, the request is blocked by the accept to receive the client's request, that is, if no client is connected, the server stays in the receiving State, that is, the next code is not executed, and when the client connects in, The data input stream is used to read the messages sent by the client, and then outputs the IO stream and socket at the end. Client:

Import java.net.*;
Import java.io.*;

public class Client {

	datainputstream din;
	DataOutputStream dout;
	Socket SC;
	
	Public Client () {
		try {
			sc = new Socket ("127.0.0.1", 9999);//connection server
			dout = new DataOutputStream (sc.getoutputs Tream ()); Get data output stream
			String msg = "Hello server";
			Dout.writeutf (msg);
			Dout.close ();
			Sc.close ();
		} catch (Exception e) {
			e.printstacktrace ();
		}
	}
	public static void Main (string[] args) {
		new Client ();
	}

The same in the client code above, through the socket to connect the server, after the successful connection to the server broadcast messages, the end of the need to close IO stream and socket.

The above program, is a simple client to send messages to the server, that is, a simple one-way communication program.


two, the server side and the client send messages to each other


The above is just the client to send messages to the server, now look at the two can send messages between the program. Server side:

Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import java.net.*;

Import java.io.*;
	public class Chatserver extends JFrame implements ActionListener {JButton jb = new JButton ("send");
	JTextField JTF = new JTextField (20);
	JTextArea JTA = new JTextArea ();
	JScrollPane jsp = new JScrollPane (JTA);
	JPanel JP = new JPanel ();
	
	PrintWriter pw = null;
		Public Chatserver () {this.settitle ("server Side");
		This.setsize (350, 250);
		This.setresizable (FALSE);
		This.setvisible (TRUE); This.setdefaultcloseoperation (this.
		Exit_on_close);
		This.setlocation (500, 300);
		Jta.setdisabledtextcolor (Color.Black);
		Jb.addactionlistener (this);
		Jp.add (JTF);
		Jp.add (JB);
		Jta.setenabled (FALSE);
		This.add (JSP);
		
		This.add (JP, "South");
			try {serversocket ss = new ServerSocket (9999);
			Socket s = ss.accept ();
			InputStreamReader ISR = new InputStreamReader (S.getinputstream ());
			BufferedReader br = new BufferedReader (ISR);PW = new PrintWriter (S.getoutputstream (), true);
				while (true) {String Xinxi = Br.readline ();
			Jta.append ("Client said:" + Xinxi + "\n\r");
		} catch (Exception e) {e.printstacktrace ();
			} public void actionperformed (ActionEvent e) {//TODO auto-generated Method stub if (E.getsource () = JB) {
			String Xinxi = Jtf.gettext ();
			Jta.append ("I said to the client:" + Xinxi + "\n\r");
			Pw.println (Xinxi);
		Jtf.settext ("");
	} public static void Main (string[] args) {//TODO auto-generated method Stub new Chatserver ();
 }

}

Client:

Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import java.awt.event.KeyEvent;
Import Java.awt.event.KeyListener;
Import java.net.*;

Import java.io.*;
	public class ChatClient extends JFrame implements ActionListener {JButton jb = new JButton ("send");
	JTextField JTF = new JTextField (20);
	JTextArea JTA = new JTextArea ();
	JScrollPane jsp = new JScrollPane (JTA);
	JPanel JP = new JPanel ();
	PrintWriter pw = null;
	DataInputStream din;
	
	DataOutputStream dout;
		Public ChatClient () {This.settitle ("client");
		This.setsize (350, 250);
		This.setresizable (FALSE);
		This.setvisible (TRUE); This.setdefaultcloseoperation (this.
		Exit_on_close);
		This.setlocation (500, 300);
		Jta.setdisabledtextcolor (Color.Black);
		Jb.addactionlistener (this);
		Jp.add (JTF);
		Jp.add (JB);
		Jta.setenabled (FALSE);
		Jta.setlinewrap (TRUE);
		This.add (JSP);
		This.add (JP, "South"); Jtf.addkeylistener (New KeyListener () {@Override public void keytyped (KeyEvent arg0) {//TODO auto-generated method stub} @Override public void Keyreleas Ed (keyevent arg0) {//TODO auto-generated method stub} @Override public void keypressed (KeyEvent E
				{int key = E.getkeycode ();
					if (key = =) {String Xinxi = Jtf.gettext ();
					Jta.append ("I said to the server:" + Xinxi + "\ r \ n");
					try {dout.writeutf (Xinxi);
					catch (IOException E1) {e1.printstacktrace ();
				} jtf.settext ("");
		}
				
			}
		});
			try {socket s = new Socket ("127.0.0.1", 8888);
			DIN = new DataInputStream (S.getinputstream ());
			Dout = new DataOutputStream (S.getoutputstream ());
				while (true) {String Xinxi = Din.readutf ();
			Jta.append ("Server said:" + Xinxi + "\ r \ n");
		} catch (Exception e) {e.printstacktrace ();
			} public void actionperformed (ActionEvent e) {if (E.getsource () = JB) {String Xinxi = Jtf.gettext (); if (!xinxi.equals ("")) {jta.append ("My serversaid: "+ Xinxi +" \ r \ n ");
				try {dout.writeutf (Xinxi);
				catch (IOException E1) {e1.printstacktrace ();
			} jtf.settext ("");
	} else {}}} public static void Main (string[] args) {new chatclient ();
 }

}


The above code is written in the server-side and the client can send messages of a program, through a while dead loop to receive messages from the client or server side, and output to the JTextArea text field, the input message is by reading the text box in the content, By a button to send him to the server side or the client, two pieces of code in fact, not much.


Three, multiple clients are connected to the server side at the same time


A server can only receive a request from the client, which is clearly not enough to meet our requirements, then, how to implement multiple clients simultaneously connected to the server side. This is going to be a thread, and whenever the server receives a request from the client, we create a thread that allows the thread to handle the client, and we can do this:

while (flag) {
		try {
			Socket sc = ss.accept ();
			Serverthread st = new Serverthread (SC);
			St.start ();
		} catch (Exception e) {
			e.printstacktrace ();
		}
	}
This allows you to handle the problem of multiple clients connecting to the server side at the same time. But then. We want to send a message between the client and the client. Then need the server side of the bridge, a client sent the message to the server side, the server to send the message to another client, then the server how to know I want to send the message is sent to this client. So to do, we create a vector object to hold the thread that is currently connected to the server, and then when a client wants to send a message to another client, the vector is traversed to find the client, and then the client message can be sent.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.