① 用Socket編程實現一個基於C/S的應用
例子一:
1 客戶端的程序
package net3;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args){
try{
System.out.println("連接到伺服器");
Socket s=new Socket("localhost",4005);
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
String str="";
String sss="";
while(true)
{
str=b.readLine();
pw.println(str);
pw.flush();
//不理睬大小寫轉換
if(str.equalsIgnoreCase("stop"))
{
System.out.println("服務停止");
break;
}
sss=br.readLine();
System.out.println(sss);
if(sss.equalsIgnoreCase("stop"))
{
System.out.println("服務停止");
break;
}
}
b.close();
br.close();
pw.close();
}
catch(IOException e){}
}
}
2 伺服器端的程序:
package net3;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args){
try{
System.out.println("伺服器正在啟動....");
ServerSocket ss=new ServerSocket(4005);
System.out.println("伺服器啟動,等待服務...");
Socket s=ss.accept();
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter bw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
String str="";
String sss="";
while(true)
{
sss=br.readLine();
System.out.println(sss);
if(sss.equalsIgnoreCase("stop"))
{
System.out.println("服務停止");
break;
}
str=r.readLine();
bw.println(str);
bw.flush();
//不理睬大小寫轉換
if(str.equalsIgnoreCase("stop"))
{
System.out.println("服務停止");
break;
}
}
br.close();
r.close();
bw.close();
}
catch(IOException e){}
}
}
例子二:
package test.socket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class TalkMe {
public static void main(String[] args) {
System.out.println("請輸入:IP地址:");
TalkMe talk = new TalkMe();
talk.listener().start();
try {
talk.talker(new BufferedReader(new InputStreamReader(System.in)).readLine()).start();
} catch (IOException e) {
e.printStackTrace();
}
}
private Thread listener(){
return new Thread() {
public void run() {
DataInputStream dataIS = null;
String clientSay;
try {
ServerSocket server = new ServerSocket(9666);
Socket socket = server.accept();
while (true) {
dataIS = new DataInputStream(socket.getInputStream());
clientSay = dataIS.readLine();
System.out.println("Other say:" + clientSay);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
private Thread talker(final String ip){
return new Thread(){
public void run() {
Socket socket = null;
InputStreamReader stdin=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(stdin);
DataInputStream dataIS = new DataInputStream(System.in);
OutputStream os;
PrintStream ps;
String say = "";
boolean flag = true;
while (flag) {
if (flag)
System.out.println("connection ....");
try {
socket = new Socket(ip, 9666);
System.out.println("connection ok.");
flag = true;
os = socket.getOutputStream();
ps = new PrintStream(os);
while (true) {
say = dataIS.readLine();
ps.println(say);
}
} catch (UnknownHostException e) {
try {
sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
}
}
}
};
}
}
② 用java做cs項目一定會用到socket編程嗎
一般都會,當然會用一些框架的話 不需要接觸到那麼底層的東西
③ java socket編程cs無法連接
不知道你的無法連接是怎麼判斷的(先啟動服務端,再啟動客戶端),我這里是可以連接的(用127.0.0.1本地測試,改成本地真實IP也是可以的);如果你的無法連接是以沒有收到客戶端發的消息,那麼就不對了,其實已經連接上了,只不過你的代碼服務端和客戶端有各種阻塞問題,寫得不對,導致程序一直「卡」在某個地方,所以沒有任何消息顯示出來。如果不用線程的話,服務端和客戶端就只能是一對一的對話,而且是你說一句我說一句的情況(因為有阻塞,等待鍵盤輸入或者等待socket流的數據);
樓上那位的代碼也沒改完,socket = ss.accept(); 這句應該放在循環外面(這句會造成阻塞的,如果放在裡面,那麼樓上的代碼就只能接收一次客戶端消息),如果想寫成一個服務端接收多個客戶端的響應,那麼就必須用線程了,把ss.accept()放到主線程(1個);收消息一個線程,發消息一個線程(每個鏈接對應2個,實現收發,這樣就不會造成接收和發送互相影響了,造成等待了)。
while (true)
{
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String line = in.readLine();
out.println("you input is :" + line);
}
④ c#語言關於socket 的cs通訊
⑤ asp.net用socket給cs服務端發送消息,功能已經實現,但經常丟失數據,能幫我解決再加100分
//客戶端代碼:
private void ...()
{
string info = "服務端第:" + i + "次發送測試數據!";
IPAddress ip = IPAddress.Parse("121.14.154.38");
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(new IPEndPoint(ip, 8899), new AsyncCallback(EndConn), null);
}
private void EndConn(IAsyncResult AR)
{
socket.EndConnect(AR);
string sendStr = info;
byte[] bs = Encoding.Default.GetBytes(sendStr); //轉換編碼
int resver = socket.Send(bs, bs.Length, 0); //發送消息
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
//服務端:
byte[] recvBytes = new byte[1024];
string recvStr = "";
private void ...()
{
IPAddress ip = IPAddress.Parse(strIP);
IPEndPoint ipe = new IPEndPoint(ip, 8889);
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipe); //綁定IP和埠
socket.Listen(5); //開始監聽
temp = socket.Accept();
recvBytes = new byte[1024];
temp.BeginReceive(recvBytes, 0, recvBytes.Length, 0, new AsyncCallback(EndRecv), null); //從客戶端接收消息
}
private void EndRecv(IAsyncResult AR)
{
int bytes = temp.EndReceive(AR);
recvStr += Encoding.Default.GetString(recvBytes, 0, bytes);
temp.BeginReceive(recvBytes, 0, recvBytes.Length, 0, new AsyncCallback(EndRecv), null); //從客戶端接收未發完的消息
}
丟失數據可能是兩個原因造成的:
一.你的發送和接收都設置了超時,可能在數據還沒有發送或接收完畢就停止
了。我幫你把Socket操作改成非同步的了,這樣不用設置超時也不會阻塞你的
主線程;
二.接收數據的時候,你只收一次,也就是只接收了一個緩沖區大小的數據,這
也可能造成數據丟失;
PS:因為沒有你的源碼,這段代碼是我隨手改的,沒有調試過,有什麼問題的話
請說明。
⑥ c++有何技術可以實現cs架構,比如socket
如果資料庫開放,並且在伺服器端不需要做其他處理,直接insert吧。
如果還需要在伺服器端decode,正常的網路通信就可以:伺服器端開監聽埠,客戶端把收集到的信息發過去,伺服器端做信息處理,入庫。這中間的技術都是最基礎的,c++/c網路編程。
⑦ 用Java的socket編程實現c/s結構程序
今天太晚了,改天給你做一個,記得提醒我,這個如果只是要個簡單的,我半個小時就搞定了
給我個郵箱
現在給貼出我的代碼: 整個結構分兩個工程
1。服務端工程NioServer.java: 採用nio 方式的非同步socket通信,不僅可以實現你的伺服器還可以讓你多學習一下什麼是nio
2。客戶端工程UserClient.java: 採用Swing技術畫了一個簡單的UI界面,比較土,原因是我沒那麼多時間去設計界面,你需要的話可以自己去修改得漂亮點,相信不難
現在貼工程1:
package com.net;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class NioServer {
public static final int SERVERPORT=5555;
public static final String USERNAME="wangrong";
public static final String PASSWORD="123456";
public static final String ISACK="ACK";
public static final String ISNAK="NAK!";
// Selector selector;//選擇器
// SelectionKey key;//key。 一個key代表一個Selector 在NIO通道上的注冊,類似主鍵;
// //取得這個Key後就可以對Selector在通道上進行操作
private ByteBuffer echoBuffer = ByteBuffer.allocate( 1024 );// 通道數據緩沖區
public NioServer(){
}
public static void main(String[] args) throws IOException {
NioServer ns=new NioServer();
ns.BuildNioServer();
}
public void BuildNioServer() throws IOException{
/////////////////////////////////////////////////////////
///////先對服務端的ServerSocket進行注冊,注冊到Selector ////
/////////////////////////////////////////////////////////
ServerSocketChannel ssc = ServerSocketChannel.open();//新建NIO通道
ssc.configureBlocking( false );//使通道為非阻塞
ServerSocket ss = ssc.socket();//創建基於NIO通道的socket連接
//新建socket通道的埠
ss.bind(new InetSocketAddress("127.0.0.1",SERVERPORT));
Selector selector=Selector.open();//獲取一個選擇器
//將NIO通道選綁定到擇器,當然綁定後分配的主鍵為skey
SelectionKey skey = ssc.register( selector, SelectionKey.OP_ACCEPT );
////////////////////////////////////////////////////////////////////
//// 接收客戶端的連接Socket,並將此Socket也接連注冊到Selector ////
///////////////////////////////////////////////////////////////////
while(true){
int num = selector.select();//獲取通道內是否有選擇器的關心事件
if(num<1){continue; }
Set selectedKeys = selector.selectedKeys();//獲取通道內關心事件的集合
Iterator it = selectedKeys.iterator();
while (it.hasNext()) {//遍歷每個事件
try{
SelectionKey key = (SelectionKey)it.next();
//有一個新聯接接入事件,服務端事件
if ((key.readyOps() & SelectionKey.OP_ACCEPT)
== SelectionKey.OP_ACCEPT) {
// 接收這個新連接
ServerSocketChannel serverChanel = (ServerSocketChannel)key.channel();
//從serverSocketChannel中創建出與客戶端的連接socketChannel
SocketChannel sc = serverChanel.accept();
sc.configureBlocking( false );
// Add the new connection to the selector
// 把新連接注冊到選擇器
SelectionKey newKey = sc.register( selector,
SelectionKey.OP_READ );
it.remove();
System.out.println( "Got connection from "+sc );
}else
//讀客戶端數據的事件,此時有客戶端發數據過來,客戶端事件
if((key.readyOps() & SelectionKey.OP_READ)
== SelectionKey.OP_READ){
// 讀取數據
SocketChannel sc = (SocketChannel)key.channel();
int bytesEchoed = 0;
while((bytesEchoed = sc.read(echoBuffer))> 0){
System.out.println("bytesEchoed:"+bytesEchoed);
}
echoBuffer.flip();
System.out.println("limet:"+echoBuffer.limit());
byte [] content = new byte[echoBuffer.limit()];
echoBuffer.get(content);
String result=new String(content);
doPost(result,sc);
echoBuffer.clear();
it.remove();
}
}catch(Exception e){}
}
}
}
public void doPost(String str,SocketChannel sc){
boolean isok=false;
int index=str.indexOf('|');
if(index>0){
String name=str.substring(0,index);
String pswd=str.substring(index+1);
if(pswd==null){pswd="";}
if(name!=null){
if(name.equals(USERNAME)
&& pswd.equals(PASSWORD)
){
isok=true;
}else{
isok=false;
}
}else{
isok=false;
}
}else{
isok=false;
}
String result="";
if(isok){
result="ACK";
}else{
result="NAK!";
}
ByteBuffer bb = ByteBuffer.allocate( result.length() );
bb.put(result.getBytes());
bb.flip();
try {
sc.write(bb);
} catch (IOException e) {
e.printStackTrace();
}
bb.clear();
}
}
下面貼工程2
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class UserClient implements ActionListener{
JFrame jf;
JPanel jp;
JLabel label_name;
JLabel label_pswd;
JTextField userName;
JButton jb;
JPasswordField paswrd;
JLabel hintStr;
public UserClient (){
jf=new JFrame("XXX 登陸系統");
jp=new JPanel();
jf.setContentPane(jp);
jf.setPreferredSize(new Dimension(350,220));
jp.setPreferredSize(new Dimension(350,220));
jp.setBackground(Color.gray);
label_name=new JLabel();
label_name.setPreferredSize(new Dimension(150,30));
label_name.setText("請輸入帳戶(數字或英文):");
userName=new JTextField();
userName.setPreferredSize(new Dimension(150,30));
jp.add(label_name);
jp.add(userName);
label_pswd=new JLabel();
label_pswd.setPreferredSize(new Dimension(150,30));
label_pswd.setText("請輸入密碼:");
jp.add(label_pswd);
paswrd=new JPasswordField();
paswrd.setPreferredSize(new Dimension(150,30));
jp.add(paswrd);
jb=new JButton("OK");
jb.setPreferredSize(new Dimension(150,30));
jb.setText("確 定");
jb.addActionListener( this);
jp.add(jb);
hintStr=new JLabel();
hintStr.setPreferredSize(new Dimension(210,40));
hintStr.setText("");
hintStr.setForeground(Color.RED);
jp.add(hintStr);
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private String name;
private String pswd;
public void actionPerformed(ActionEvent e) {
name=userName.getText().trim();
pswd=new String(paswrd.getPassword());
if(pswd==null){
pswd="";
}else{
pswd=pswd.trim();
}
if(name!=null && name.length()>0){
hintStr.setText("正在驗證客戶端,請稍候...");
start();
}
}
OutputStream os;
Socket s;
InputStream is;
public void start(){
//建立聯網線程
new Thread(new Runnable(){
public void run() {
try {
s=new Socket("127.0.0.1",5555);
//寫
os=s.getOutputStream();
os.write(name.getBytes());
os.write('|');//用戶名與密碼用"|"分隔
os.write(pswd.getBytes());
os.flush();
//讀內容
Thread.sleep(1000);
is=s.getInputStream();
int len=is.available();
System.out.println("len:"+len);
byte[] bytes=new byte[len];
is.read(bytes);
String resut=new String(bytes);
System.out.println("resut:"+resut);
//TODO 這里通過返回結果處理
if(resut.equals("ACK")){
hintStr.setText("驗證成功,歡迎光臨!");
}else{
paswrd.setText(null);
hintStr.setText("用戶名或密碼錯誤,請重新輸入");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
// try {
// os.close();
// is.close();
// s.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
}).start();
}
public static void main(String[] args) {
new UserClient();
}
}
⑧ 基於socket 的C/S 程序如何在同一台機器上實現通信
為什麼客戶端和服務端使用同一個埠號,使用同一個埠號當然不能正常通信啊,在同一台機器上,一個埠號只能是屬於一個進程。你的客戶端的埠號應該是讓系統自動分配
⑨ 用C#編寫伺服器的socket模塊,按照『C#基於Socket的CS模式的完整例子』上面的內容進行調試,出現兩個問題
是點擊關閉後仍舊在調試---這個問題是你在關閉的時候沒有退出線程,你需要在close事件里關閉socket,退出線程,或者直接調用你的Dispose方法
客戶端收不到消息因為你沒貼客戶端的源碼,看不出是什麼問題